﻿//@LOGIN.CS

//subscribedCols = new List<string>(50);

//The Shown event occured after the load event, the main difference is not in the visibility 
//but in state of the form (width,hieght,..etc). I will give you an example to clarify if we create a form 
//with default size 100,200 and set the windowstate = Maximized in the load event the size will be 100,200 
//but in shown event the size will be your screen size
//tePassword.LostFocus += new EventHandler(tePassword_LostFocus);

//cvrEmpty = new ConditionValidationRule();
//cvrEmpty.ConditionOperator = ConditionOperator.IsNotBlank;
//cvrEmpty.ErrorText = "Lütfen bir değer giriniz.";

//this.ActiveControl = tePassword;

//dxValidationProvider1.SetValidationRule(teUsername, cvrEmpty);
//dxValidationProvider1.SetValidationRule(tePassword, cvrEmpty);


//XForm.newThread = null;
//WhoAmI = 0; //static constructor ı çalıştırmak için!

//using(System.IO.StreamWriter writer=new System.IO.StreamWriter(@"d:\roll.txt",true))
//{
//foreach(MyData.xStoklarOzetRow r in ds.xStoklarOzet.Select("QtySelected>0", string.Empty))
//    writer.WriteLine(r.RollId);
//}

//beTalepId.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(beTalepId_ButtonClick);
//beTalepId.Properties.ReadOnly = true;
//beTalepId.EditValueChanged += new EventHandler(beTalepId_EditValueChanged);

//void beTalepId_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
//       {
//           using (_Talepler yt = new _Talepler())
//           {
//               if (yt.ShowDialog() == DialogResult.OK)
//               {
//                   beTalepId.EditValue = yt.TalepId;
//               }

//           }
//       }

//       void beTalepId_EditValueChanged(object sender, EventArgs e)
//       {
//           btnKaydet.Enabled = (beTalepId.EditValue != null);
//           TalepId = intParse(beTalepId.EditValue);

//           ds.Clear();
//           GetDetails("TalepLines", "GetTalepLines", TalepId);
//           gvTalepLines.BestFitColumns();
//       }

//RepositoryItem riT = RI(Rp.Tela);
//RepositoryItem riK = RI(Rp.V_Kumas);
//DataTable dtT = (DataTable)((RepositoryItemGridLookUpEdit)riT).DataSource;
//DataTable dtV = (DataTable)((RepositoryItemGridLookUpEdit)riK).DataSource;
//dtV.Merge(dtT);
//RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();
//ri.DisplayMember = "Name";
//ri.ValueMember = "ProductId";
//ri.NullText = string.Empty;
//ri.DataSource = dtV;
//ri.PopulateViewColumns();
//ri.BestFitMode = BestFitMode.BestFitResizePopup;
//ri.View.OptionsView.ColumnAutoWidth = false;
//ri.View.BestFitColumns();
//gvCELines.Columns["ProductId"].ColumnEdit = ri;

//void tePassword_LostFocus(object sender, EventArgs e)
//{
//    strUserId = CheckCredentials(teUsername.Text, tePassword.Text);
//    hyperLinkEdit1.Visible = (strUserId != string.Empty);
//}

//ConditionValidationRule cvrEmpty;

//LINQ
//var xml = new XElement("DictionaryContents",     myDict.Select(kvp => new XElement(kvp.Key, kvp.Value)));  return xml.ToString(); 

//@REPOSITORYMANAGER
//if(dt.TableName == "ProductCategory")
//    ri.View.CustomRowFilter += new DevExpress.XtraGrid.Views.Base.RowFilterEventHandler(gle_CustomRowFilter);

//            ri.View.OptionsView.RowAutoHeight = true;

//ri.View.Appearance.EvenRow.BackColor =
//    (DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName == "Office 2007 Black" ? System.Drawing.Color.WhiteSmoke : System.Drawing.Color.FromArgb(250, 245, 245));


/*                switch (dt.TABLE_NAME)
                {
                    case "V_Aksesuar": InitRepositoryItemGridLookUpEdit(riAProduct, dsi.V_Aksesuar, "ProductId", "ProductId"); break;
                    case "V_Contact": InitRepositoryItemGridLookUpEdit(riContact, dsi.V_Contact, "UserId", "UserId"); break;
                    case "V_Customer": InitRepositoryItemGridLookUpEdit(riCustomer, dsi.V_Customer, "Name", "Marka"); break;
                    case "V_Employee": InitRepositoryItemGridLookUpEdit(riEmployee, dsi.V_Employee, "Name", "EmployeeId"); break;
                    case "V_User": InitRepositoryItemGridLookUpEdit(riUser, dsi.V_User, "Username", "UserId"); break;
                    case "V_Kumas": InitRepositoryItemGridLookUpEdit(riKProduct, dsi.V_Kumas, "ProductId", "ProductId"); break;
                    case "V_Model": InitRepositoryItemGridLookUpEdit(riModel, dsi.V_Model, "Name", "ModelId"); break;
                    case "V_SalesAgent": InitRepositoryItemGridLookUpEdit(riSalesAgent, dsi.V_SalesAgent, "SalesAgentId", "SalesAgentId"); break;
                    case "V_SalesPerson": InitRepositoryItemGridLookUpEdit(riSalesPerson, dsi.V_SalesPerson, "FirstName", "SalesPersonId"); break;
                    case "V_Vendor": InitRepositoryItemGridLookUpEdit(riAVendor, riKVendor, dsi.V_Vendor, "Name", "VendorId"); break;
                    case "Atelye": InitRepositoryItemGridLookUpEdit(riAtelye, dsi.Atelye, "Name", "DepoId"); break;

                    case "SiparisDurumu1": InitRepositoryItemGridLookUpEdit(riSiparisDurumu1, dsi.SiparisDurumu1, "Name", "SiparisDurumu1Id"); break;
                    case "SiparisDurumu2": InitRepositoryItemGridLookUpEdit(riSiparisDurumu2, dsi.SiparisDurumu2, "Name", "SiparisDurumu2Id"); break;
                    case "YuklemeSekli": InitRepositoryItemGridLookUpEdit(riYuklemeSekli, dsi.YuklemeSekli, "Name", "YuklemeSekliId"); break;
                    case "TeslimSekli": InitRepositoryItemGridLookUpEdit(riTeslimSekli, dsi.TeslimSekli, "Name", "TeslimSekliId"); break;

                    case "BelgeTipi": InitRepositoryItemGridLookUpEdit(riBelgeTipi, dsi.BelgeTipi, "Name", "BelgeTipiId"); break;
                    case "Brand": InitRepositoryItemGridLookUpEdit(riBrand, dsi.Brand, "Name", "BrandId"); break;
                    case "Carrier": InitRepositoryItemGridLookUpEdit(riCarrier, dsi.Carrier, "Name", "CarrierId"); break;
                    case "ContactType": InitRepositoryItemGridLookUpEdit(riContactType, dsi.ContactType, "Name", "ContactTypeId"); break;
                    case "Country": InitRepositoryItemGridLookUpEdit(riCountry, dsi.Country, "Name", "CountryId"); break;
                    case "Culture": InitRepositoryItemGridLookUpEdit(riCulture, dsi.Culture, "Name", "CultureId"); break;
                    case "Currency": InitRepositoryItemGridLookUpEdit(riCurrency, dsi.Currency, "Abbr", "CurrencyId"); break;
                    case "Dagilim": InitRepositoryItemGridLookUpEdit(riDagilim, dsi.Dagilim, "Name", "DagilimId"); break;
                    case "DeliveryTerm": InitRepositoryItemGridLookUpEdit(riDeliveryTerm, dsi.DeliveryTerm, "Name", "DeliveryTermId"); break;
                    case "Department": InitRepositoryItemGridLookUpEdit(riDepartment, dsi.Department, "Name", "DepartmentId"); break;
                    case "FDepo": InitRepositoryItemGridLookUpEdit(riFDepo, dsi.FDepo, "Name", "DepoId"); break;
                    case "HareketTipi": InitRepositoryItemGridLookUpEdit(riHareketTipi, dsi.HareketTipi, "Name", "HareketTipiId"); break;
                    //case "Joker": InitRepositoryItemLookUpEdit(riJoker, dsi.Joker, "Name"); break;
                    case "KullanimYeri": InitRepositoryItemGridLookUpEdit(riKullanimYeri, dsi.KullanimYeri, "Name", "KullanimYeriId"); break;
                    case "ModelCategory": InitRepositoryItemGridLookUpEdit(riModelCategory, dsi.ModelCategory, "Name", "ModelCategoryId"); break;
                    case "ModelSubcategory": InitRepositoryItemGridLookUpEdit(riModelSubcategory, dsi.ModelSubcategory, "Name", "ModelSubcategoryId"); break;
                    case "Module": InitRepositoryItemGridLookUpEdit(riModule, dsi.Module, "Name", "ModuleId"); break;
                    case "Origin": InitRepositoryItemGridLookUpEdit(riOrigin, dsi.Origin, "Name", "OriginId"); break;
                    case "PaymentMethod": InitRepositoryItemGridLookUpEdit(riPaymentMethod, dsi.PaymentMethod, "Abbr", "PaymentMethodId"); break;
                    case "PaymentTerm": InitRepositoryItemGridLookUpEdit(riPaymentTerm, dsi.PaymentTerm, "Name", "PaymentTermId"); break;
                    case "ProductCategory": InitRepositoryItemGridLookUpEdit(riProductCategory, riAProductCategory, riKProductCategory, dsi.ProductCategory, "Name", "ProductCategoryId"); break;
                    case "Sezon": InitRepositoryItemGridLookUpEdit(riSezon, dsi.Sezon, "Name", "SezonId"); break;
                    case "Shelf": InitRepositoryItemGridLookUpEdit(riShelf, dsi.Shelf, "Name", "ShelfId"); break;
                    case "ShipMethod": InitRepositoryItemGridLookUpEdit(riShipMethod, dsi.ShipMethod, "Name", "ShipMethodId"); break;
                    case "StokTipi": InitRepositoryItemGridLookUpEdit(riStokTipi, dsi.StokTipi, "Name", "ProductCategoryId"); break;
                    case "UnitMeasure": InitRepositoryItemGridLookUpEdit(riUnitMeasure, dsi.UnitMeasure, "Name", "UnitMeasureId"); break;

                    case "KarbelKalite": InitRepositoryItemGridLookUpEdit(riKarbelKalite, dsi.KarbelKalite, "Name", "KarbelKaliteId");
                        riKarbelKalite.View.OptionsView.AllowCellMerge = true;
                        riKarbelKalite.View.Columns["KarbelKaliteId"].Visible = false;
                        riKarbelKalite.PopupFormMinSize = new System.Drawing.Size(825, 500);

                        //riKarbelKalite.View.BeginSort();
                        //riKarbelKalite.View.Columns["GrupAdi"].GroupIndex = riKarbelKalite.View.SortInfo.GroupCount;
                        //riKarbelKalite.View.EndSort();
                        break;
                }
 */


//public static RepositoryItemGridLookUpEdit riKarbelKalite = new RepositoryItemGridLookUpEdit();



//XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//ns.Add(String.Empty, String.Empty);
//StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
//XmlTextWriter tw = new MyXmlTextWriter(sw);

//ConfExpert.Datasets.MyData dsi2 = new ConfExpert.Datasets.MyData();
//dsi2.LookUp.Merge(dsi.LookUp);
//dsi2.WriteXml(tw, XmlWriteMode.IgnoreSchema);




//ri.View.Columns.Clear();
/*
int visibleindex = 0;
foreach (DataColumn column in dt.Columns)
{
    string c = column.Caption;
    if (c != "UserId" && c != "TS" && c != "Deleted")
    {
        GridColumn col = ri.View.Columns.AddField(c);

        if (c == "Photo")
        {
            col.ColumnEdit = new RepositoryItemPictureEdit();
            ((RepositoryItemPictureEdit)col.ColumnEdit).SizeMode = PictureSizeMode.Zoom;
            col.ColumnEdit.NullText = " ";
        }
        else if (col.FieldName != valueMember && !(dt.TableName == "ProductCategory" && col.FieldName == "BrandId"))
            //MapColumn(col, st);

            col.VisibleIndex = visibleindex++;
        col.Caption = c;
    }
}
*/


//@XForm.CS

/*
static XForm()
{
Work splashWork = new Work();
ThreadStart threadDelegate = new ThreadStart(splashWork.DoMoreWork);
Thread newThread = new Thread(threadDelegate);
newThread.InitializeTimer();

th.ApartmentState = ApartmentState.STA;
th.IsBackground=true;
Thread.Sleep(1000);


newThread.Abort();
}



string GetParentPage(Control gridControl)
{
    Control parent = gridControl.Parent;
    while (parent != null)
    {
        if (parent is DevExpress.XtraTab.XtraTabPage)
            return ((DevExpress.XtraTab.XtraTabPage)parent).Name;
        else if (parent is DevExpress.XtraEditors.XtraForm)
            return ((DevExpress.XtraEditors.XtraForm)parent).Name;
        parent = parent.Parent;
    }
    return null;
}

static internal void BestFitColumns(ref DevExpress.XtraEditors.LookUpEdit lookUpEdit)
{
    if (lookUpEdit.Properties.Columns.Count == 0)            
        return;

    int totalWidth = 0;
    int columnWidth = 0;
    Graphics g = lookUpEdit.CreateGraphics();

    for (int intColumn = 0; intColumn <= lookUpEdit.Properties.Columns.Count - 1; intColumn++)
    {
        DevExpress.XtraEditors.Controls.LookUpColumnInfo column = lookUpEdit.Properties.Columns(intColumn);
        if (column.Visible)
        {
            column.Caption = column.Caption + "00000";
            columnWidth = lookUpEdit.Properties.MeasureColumn(g, column);
            column.Width = columnWidth;
            totalWidth += columnWidth;
            column.Caption = Strings.Left(column.Caption, Strings.Len(column.Caption) - 5);
        }
    }

    g.Dispose();

    // the + 4 is the extra pixels for the popup box shadow

    lookUpEdit.Properties.PopupWidth = totalWidth + SystemInformation.VerticalScrollBarWidth + 4;
}


if (gridview.Columns.Count > 0)
{
    if (st != StokTipi.Other && gridview.Name != "ProductBase" && gridview.Columns.Contains(gridview.Columns["ProductId"]))
    {
        if (gridview.Columns.Contains(gridview.Columns["ProductCategoryId"]))
        {
            bs.Filter = "ProductCategoryId=" + ((int)st).ToString();
            gridview.Columns["ProductCategoryId"].Visible = false;
        }
        StokKoduVeRengiEkle(gridview, st);
        gridview.CustomUnboundColumnData += new CustomColumnDataEventHandler(gv_CustomUnboundColumnData);
    }
}

 * 
 * 
        string masterGridKeyField = "ProductId";
        string displayFields = ";StokKodu;StokTip;StokDesenNo;StokRengi;Boy;";   //.Split(';');
        public void gv_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e)
        {
            ColumnView view = sender as ColumnView;

            if (displayFields.Contains(";" + e.Column.FieldName + ";") && e.IsGetData)
            {
                RepositoryItemGridLookUpEdit riGridLookUp = view.Columns[masterGridKeyField].ColumnEdit as RepositoryItemGridLookUpEdit;
                object currentKey = view.GetListSourceRowCellValue(e.ListSourceRowIndex, masterGridKeyField);
                if (currentKey != null)
                {
                    int lookUpGridSelectedRowIndex = riGridLookUp.GetIndexByKeyValue(currentKey);
                    if (lookUpGridSelectedRowIndex > -1)
                        e.Value = ((riGridLookUp.DataSource as DataTable).Rows[lookUpGridSelectedRowIndex] as DataRow)[e.Column.FieldName];
                    else
                        e.Value = "";
                }
            }
        }

 *         //public static DataViewRowState Added = DataViewRowState.Added | DataViewRowState.ModifiedCurrent;
        //public static DataViewRowState Deleted = DataViewRowState.Deleted;

        public static Thread newThread;

   case "DepomdaNeVar":
        GridColumn col = gridview.Columns["Qty"];
        col.ColumnEdit = new RepositoryItemProgressBar();
        ((RepositoryItemProgressBar)col.ColumnEdit).ShowTitle = true;
        ((RepositoryItemProgressBar)col.ColumnEdit).PercentView = false;
        ((RepositoryItemProgressBar)col.ColumnEdit).Maximum = 500;
        //Qty'nin yanına yeni bir sütun ekle ve onu ProgressBar olarak göster!
        //((RepositoryItemProgressBar)col.ColumnEdit).ReadOnly = false;


 * 
        public void StokKoduVeRengiEkle(GridView gv, StokTipi st)
        {
            //gv.GridControl.ForceInitialize();
            int idx = gv.Columns["ProductId"].VisibleIndex;
            switch (st)
            {
                case StokTipi.Kumas:
                    MyAddField(gv, "StokTip", ref idx);
                    MyAddField(gv, "StokDesenNo", ref idx);
                    MyAddField(gv, "StokRengi", ref idx);
                    break;
                case StokTipi.Aksesuar:
                    MyAddField(gv, "StokKodu", ref idx);
                    MyAddField(gv, "StokRengi", ref idx);
                    MyAddField(gv, "Boy", ref idx);
                    break;
            }
        }

        public void MyAddField(GridView gv, string FieldName, ref int idx)
        {
            GridColumn unb = gv.Columns.AddField(FieldName);
            unb.UnboundType = DevExpress.Data.UnboundColumnType.String;
            //unbColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //unbColumn.DisplayFormat.FormatString = "c";
            unb.OptionsColumn.AllowEdit = false;
            unb.AppearanceCell.BackColor = Color.LemonChiffon;
            unb.VisibleIndex = ++idx;

            if (gv.Name.Contains("bgv"))
                ((BandedGridView)gv).Bands[0].Columns.Add((BandedGridColumn)unb);
        }
 * 
 * 
 * 
 * 
 * 
 *         public void _CreateDataRelation(params string[] Names)
        {
            if (ds.Tables.Contains(Names[0]) && ds.Tables.Contains(Names[1]))
            {
                //FK_PurchaseOrderLines_PurchaseOrder_PurchaseOrderId                
                DataRelation rel = new System.Data.DataRelation("FK_" + Names[0] + "_" + Names[1] + "_" + Names[2],
                    ds.Tables[Names[1]].Columns[Names.Length > 3 ? Names[3] : Names[2]],
                    ds.Tables[Names[0]].Columns[Names[2]]);
                //ds.Relations.Add(rel);

                ForeignKeyConstraint ParentFK = new ForeignKeyConstraint("FK_" + Names[0] + "_" + Names[1] + "_" + Names[2], rel.ParentColumns, rel.ChildColumns);
                ParentFK.UpdateRule = Rule.Cascade;
                rel.ChildTable.Constraints.Add(ParentFK);
            }
        }

 * 
 * 
 * 
*                         if (col.ColumnEdit is RepositoryItem)
        {
            (col.ColumnEdit as RepositoryItemLookUpEdit).Properties.TextEditStyle = TextEditStyles.Standard;
            if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
            {
            (col.ColumnEdit as RepositoryItemGridLookUpEdit).Properties.TextEditStyle = TextEditStyles.Standard;
            (col.ColumnEdit as RepositoryItemGridLookUpEdit).Properties.AutoSearchColumnIndex = 1;
            }


            buna gerek var mı?
            col.ColumnEdit.EditValueChanged += new EventHandler(ri_EditValueChanged);
            subscribedCols.Add(col.FieldName);
        }
 *
 * 
 * 
         //public virtual void gle_CustomRowFilter(object sender, DevExpress.XtraGrid.Views.Base.RowFilterEventArgs e)
        //{
        //DataRow rowTL = carsDBDataSet.Cars[e.ListSourceRow];
        //if ((int)rowTL["ID"] > 0 && (decimal)rowTL["Price"] < 20000)
        //{
        //    e.Visible = false;
        //    e.Handled = true;
        //}
        //}
* 
 * 
 * 
 * 
 *        public static string FormatF2(int N)
        {
            return "F" + String.Format("{0:00}", N);
        }

 * 
 
            //if (col.ColumnEdit is RepositoryItemLookUpEdit)
            //    (col.ColumnEdit as RepositoryItemLookUpEdit).ShowDropDown = ShowDropDown.DoubleClick;
            //else if (col.ColumnEdit is RepositoryItemGridLookUpEdit)
            //    (col.ColumnEdit as RepositoryItemGridLookUpEdit).ShowDropDown = ShowDropDown.DoubleClick;
* 
 * 
 * 
            //"A strip is a single image that is treated as multiple images arranged side-by-side"

            //IMAGESTRIP kullanalım!
            //imageList1.Images.Clear();
            //imageList1.Images.AddStrip(new Bitmap(@"yetki:\\foo.bmp"));
            //navBarControl1.Invalidate();

            //    public void AddStripToCollection()
            //{
            //    // Add the image strip.
            //    Bitmap bitmaps = new Bitmap(typeof(PrintPreviewDialog), "PrintPreviewStrip.bmp");
            //    imageList1.Images.AddStrip(bitmaps);

            //    // Iterate through the images and display them on the form.
            //    for (int i = 0; i < imageList1.Images.Count; i++) {

            //        imageList1.Draw(this.CreateGraphics(), new Point(10,10), i);
            //        Application.DoEvents();
            //        System.Threading.Thread.Sleep(1000);

            //    }
            //}


 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * @YETKİ
 *
 *          private void Yetki_Load(object sender, EventArgs e)
        {
            TAM.PermissionsTableAdapter.Fill(ds.Permissions);
            TAM.UserPermissionsTableAdapter.Fill(ds.UserPermissions);
            ds.Permissions.Columns.Add("SEÇ", typeof(Boolean));

            bsUserPermissions = new BindingSource(ds, "UserPermissions");
            bsPermissions = new BindingSource(ds, "Permissions");
            InitGridView(gvUP, bsUserPermissions);
            gvUP.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;

            InitGridView(gvP, bsPermissions);
            gvP.Columns["FormId"].Visible = gvP.Columns["PermissionId"].Visible = gvP.Columns["TS"].Visible = gvUP.Columns["Permission"].Visible = false;
            gvP.Columns["SEÇ"].VisibleIndex = 0;
            gvP.OptionsView.EnableAppearanceEvenRow = false;
            gvP.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gvP_RowStyle);
            bsUserPermissions.CurrentChanged += new EventHandler(bsUserPermissions_CurrentChanged);

            gvP.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(gvP_CellValueChanged);
            bsUserPermissionsCurrentChanged();
        }

        void gvP_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int yetki = 0;
            DataRow dr = null;
            for (int i = 0; i < gvP.RowCount; i++)
            {
                dr = gvP.GetDataRow(i);
                if (dr["SEÇ"].ToString() == Boolean.TrueString)
                    yetki += (int)Math.Pow(2, (int)dr["PermissionId"]);
            }
            ((ConfExpert.Datasets.MyData.UserPermissionsRow)((DataRowView)bsUserPermissions.Current).Row).Permission = yetki;
        }

        int FormId = 1;
        void gvP_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
                if (((sender as GridView).GetRowCellDisplayText(e.RowHandle, "SEÇ")) == "Checked")
                    e.Appearance.BackColor = Color.LightYellow;
        }

        
        private BitArray bitArray = new BitArray(32);

        public int BitArray
        {
            get
            {
                int[] array = new int[1];
                bitArray.CopyTo(array, 0);
                return array[0];
            }
            set
            {
                bitArray = new BitArray(new int[] { value });
            }
        }
        BitArray larrBits = new BitArray(System.BitConverter.GetBytes(123)); 
        
        void bsUserPermissions_CurrentChanged(object sender, EventArgs e)
        {
            bsUserPermissionsCurrentChanged();
        }

        private void bsUserPermissionsCurrentChanged()
        {
            if (bsUserPermissions.Current != null)
                if (gvUP.GetRowCellValue(gvUP.FocusedRowHandle, "FormId") != DBNull.Value)
                {
                    ConfExpert.Datasets.MyData.UserPermissionsRow upRow = ((DataRowView)bsUserPermissions.Current).Row as ConfExpert.Datasets.MyData.UserPermissionsRow;
                    FormId = upRow.FormId;
                    int perm = upRow.IsPermissionNull() ? 0 : upRow.Permission;
                    bsPermissions.Filter = "FormId = " + FormId;

                    foreach (DataRow dr in ds.Permissions.Select("FormId = " + FormId))
                        dr["SEÇ"] = (perm & (int)Math.Pow(2, (int)dr["PermissionId"])) > 0;
                }
        }

 * 
 * 
 * 
 *         //void gvKst3_DoubleClick(object sender, EventArgs e)
        //{
        //    GridView view = ((GridView)sender);
        //    GridHitInfo hi = view.CalcHitInfo(view.GridControl.PointToClient(MousePosition));
        //    if (hi.InRow || hi.InRowCell)
        //    {
        //        DataRow curr = view.GetFocusedDataRow();
        //        SipNo = curr["SipNo"].ToString();

        //        bsKST.Filter = "SipNo = '" + SipNo + "'" +
        //            (" AND MarkaId " + (curr["MarkaId"] != DBNull.Value ? "= " + curr["MarkaId"].ToString() : "is null")) +
        //            (" AND UreticiId " + (curr["UreticiId"] != DBNull.Value ? "= " + curr["UreticiId"].ToString() : "is null")) +
        //            (" AND SipVerenId " + (curr["SiparisEdenId"] != DBNull.Value ? "= " + curr["SiparisEdenId"].ToString() : "is null")) +
        //            (" AND Sezon " + (curr["Sezon"].ToString() != string.Empty ? "= '" + curr["Sezon"].ToString() + "'" : " is null")); //dikkat! null vs. empty

        //        Upd(enPages.DetayListe, "- KST. " + SipNo);

        //        barManager.Items["Çağrılan satır"].PerformClick();
        //        bgvKstBestFitColumns();
        //        tabAna.SelectedTabPage = tpListe;
        //    }
        //    else
        //        Upd(enPages.DetayListe, "- KST");
        //    //                XtraMessageBox.Show("Çift tıklayarak detaya gitmek için lütfen aşağıdaki sekmelerden TÜMÜ dışında birine tıklayın.");
        //}

 * 
 * 
 * 
 *         private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == AppSession.Lookups.ProductCategory.ProductCategoryIdColumn.ColumnName)
            {
                GridView gridView = sender as GridView;

                object errorCt = gridView.GetRowCellValue(e.RowHandle, AppSession.Lookups.ProductCategory.ServisColumn.ColumnName);
                if (errorCt != DBNull.Value && (int)errorCt > 0)
                {
                    e.Appearance.BackColor = Color.Red;
                    //e.Appearance.BackColor2 = Color.Red;
                }
            }
        } 


 * 
 * 
 * 
        /*
                DataTable dtUsers;
                DataTable dtUsersRole;
                DataTable dtRoles;
                DataTable dtForms;
                DataTable dtUserPermission;
                DataTable dtPermissionsExt;
                DataTable dtFormPermission;
        
         
                private void RefreshData()
                {
                    FillData();
                    BindPermissions();
                    BindForms();
                    BindRoles();
                    BindUsersRoles();
                    BindUsers();
                }

                private void BindUsersRoles()
                {
                    //gcUsersRole.DataSource = dtUsersRole.DefaultView;
                    //gvUsersRole.PopulateColumns();

                    //foreach (GridColumn column in gvUsersRole.Columns)
                    //{
                    //    gvUsersRole.Columns[column.FieldName].Visible = false;
                    //}

                    //gvUsersRole.Columns["Name"].Visible = true;
                }

                private void BindForms()
                {
                    gcForm.DataSource = dtForms;
                    gvForm.PopulateColumns();

                    foreach (GridColumn column in gvForm.Columns)
                    {
                        column.Visible = false;
                    }

                    gvForm.Columns["Name"].Visible = true;
                }

                private void FillData()
                {
                    dtFormPermission = YetkiData.GetFormPermission();
                    dtUserPermission = YetkiData.GetUserPermissions();
                    dtPermissionsExt = YetkiData.ExtractPermission(dtUserPermission);

                    dtUsersRole = YetkiData.GetUsersRole();

                    dtUsers = YetkiData.GetUsers();
                    dtRoles = YetkiData.GetRoles();
            
                    dtForms = YetkiData.GetForms();
            
                }

                private void BindUsers()
                {
                    gcUser.DataSource = dtUsers;
                    gvUser.PopulateColumns();

                    foreach (GridColumn column in gvUser.Columns)
                    {
                        column.Visible = false;
                    }

                    gvUser.Columns["UserName"].Visible = true;

                    gcUserPermission.DataSource = dtFormPermission;

                    foreach (GridColumn column in gvUserPermission.Columns)
                    {
                        column.Visible = false;
                        column.OptionsColumn.AllowEdit = false;
                    }
            
                    gvUserPermission.Columns["Name"].Visible = true;            
                    gvUserPermission.Columns["PermissionDescription"].Visible = true;
                    gvUserPermission.Columns["Selected"].OptionsColumn.AllowEdit = true;
                    gvUserPermission.Columns["Selected"].Visible = true;
            
                    gvUserPermission.Columns["Name"].Group();

                }

                private void BindRoles()
                {
            
                    gcRole.DataSource = dtRoles.DefaultView;
                    gvRole.PopulateColumns();


                    foreach (GridColumn column in gvRole.Columns)
                    {
                        gvRole.Columns[column.FieldName].Visible = false;
                    }


                    gvRole.Columns["Name"].Visible = true;
                }

                private void BindPermissions()
                {           
                    //gcUsersPermission.DataSource = dtPermissionsExt.DefaultView;
                    //gvUsersPermission.PopulateColumns();

                    //foreach (GridColumn column in gvUsersPermission.Columns)
                    //{
                    //    gvUsersPermission.Columns[column.FieldName].Visible = false;
                    //    gvRolePermission.Columns[column.FieldName].Visible = false;
                    //}

                    //gvUsersPermission.Columns["Name"].Visible = true;
                    //gvRolePermission.Columns["Name"].Visible = true;
            
            
                }

                private void gvKullanici_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
                {
                    FilterUsers();
                }

     

                private void gvRoles_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
                {
                    FilterRoles();
                }

                private void gvForms_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
                {
                    FilterForms();
                }

                private void FilterUsers()
                {
                    if (gvUser.FocusedRowHandle < 0)
                    {
                        return;
                    }
            
                    foreach (DataRow drPermission in dtFormPermission.Rows)
                    {
                        drPermission["Selected"] = false;
                    }
            


                    int userId = (int)gvUser.GetFocusedRowCellValue("UserId");

                    //DataView dv = (DataView)gvUserRole.DataSource;
                    //dv.RowFilter = "UserId = " + userId;


                    DataRow[] drPermissions=  dtUserPermission.Select("UserId = " + userId);
                    foreach (DataRow dr in drPermissions)
                    {
                        int formtype = (int)dr["FormId"];
                        string permissionLine = dr["PermissionLine"].ToString();

                        DataRow[] drFormPermission = dtFormPermission.Select("FormId =" + formtype);
                        int counter = 0 ;
                        foreach (DataRow drPermission in drFormPermission)
                        {
                            drPermission["Selected"] = permissionLine[counter++] == '1';
                        }
                    }


                }

       
                private void FilterRoles()
                {
                    //if (gvRoles.FocusedRowHandle < 0)
                    //{
                    //    return;
                    //}

                    //int roleId = (int)gvRoles.GetFocusedRowCellValue("RoleId");

                    //DataView dv = (DataView)gvRolePermission.DataSource;
                    //dv.RowFilter = "RoleId = " + roleId;
                }

                private void FilterForms()
                {
                    //if (gvForms.FocusedRowHandle < 0)
                    //{
                    //    return;
                    //}

                    //int formtype = (int)gvRoles.GetFocusedRowCellValue("FormId");

                    //DataView dv = (DataView)gvFormPermission.DataSource;
                    //dv.RowFilter = "FormId = " + formtype;
                }

                private void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
                {
                    gvUserPermission.CloseEditor();
                    gvUserPermission.UpdateCurrentRow();

                    foreach (DataRow dr in dtForms.Rows)
                    {
                        int formtype = (int)dr["FormId"];
                        int userId = (int)dr["UserId"];
                        //string permissionLine = Session.DefaultPermissionLine;

                       //DataRow[] drPermissions =  dtUserPermission.Select("FormId = " + formtype + " and Selected=1");

                       //foreach (DataRow drPermission in drPermissions)
                       //{
                       //    int permissionOrder = (int)drPermission["PermissionOrder"];
                       //    char[] c =  permissionLine.ToCharArray();
                       //    c[permissionOrder] = '1';
                       //    permissionLine = c.ToString(); 
                       //}

                       //YetkiData.UpdateUserPermission(formtype, userId, permissionLine);
                    }
                }
         * 

 
                //ay = deGun.DateTime.AddDays(-deGun.DateTime.Day + 1);
                //bsMonthly.Filter = "Tarih >= '" + ay.ToShortDateString() + "' AND Tarih <= '" + ay.AddMonths(1).AddSeconds(-1).ToShortDateString() + "'";
                //bsYearly.Filter = "Tarih >= '" + ay.AddDays(-ay.DayOfYear + 1).ToShortDateString() + "' AND Tarih <= '" + ay.AddDays(-ay.DayOfYear + 1).AddYears(1).AddSeconds(-1).ToShortDateString() + "'";

 * 
 * 
 * 
 * void Draw2()
        {

chartControl1.Series.Clear(); 
for (int i = 0; i < dtDep.Rows.Count; i++) 
{ 
chartControl1.Series.Add(dtDep.DefaultView[i]["TaskName"].ToString(), DevExpress.XtraCharts.ViewType.Spline); 
DataTable dtAmount = new DataTable(); 
if (radioGroup1.SelectedIndex == 0) 
{ 
chartControl1.Titles[0].Text = title + " sd"; 
dtAmount = bllP2D.GetSumDay(int.Parse(dtDep.DefaultView[i]["ID"].ToString()), dt1, dt2).Tables[0]; 
} 
else if (radioGroup1.SelectedIndex == 1) 
{ 
chartControl1.Titles[0].Text = title + " sd "; 
dtAmount = bllP2D.GetSumWeek(int.Parse(dtDep.DefaultView[i]["ID"].ToString()), dt1, dt2).Tables[0]; 
} 
else if (radioGroup1.SelectedIndex == 2) 
{ 
chartControl1.Titles[0].Text = title + " sad"; 
dtAmount = bllP2D.GetSumMonth(int.Parse(dtDep.DefaultView[i]["ID"].ToString()), dt1, dt2).Tables[0]; 
} 
for (int j = 0; j < dtAmount.Rows.Count; j++) 
{ 
if (radioGroup2.SelectedIndex == 0) 
{ 
chartControl1.Series[i].Points.Add(new DevExpress.XtraCharts.SeriesPoint(dtAmount.DefaultView[j]["DateTime"].ToString(), new object[] { (dtAmount.DefaultView[j]["EligibleAmount"].ToString()) })); 
} 
else if (radioGroup2.SelectedIndex == 1) 
{ 
chartControl1.Series[i].Points.Add(new DevExpress.XtraCharts.SeriesPoint(((DateTime)(dtAmount.DefaultView[j]["DateTime"])).ToLongDateString(), new object[] { (dtAmount.DefaultView[j]["InferiorAmount"].ToString()) })); 

} 
} 
chartControl1.Series[i].Visible = true; 
}
        }
 * 
 * 
 * 
                //chartControl1.SeriesTemplate.DataFilters.Add(new DataFilter("Values", typeof(double).FullName, DataFilterCondition.NotEqual, DBNull.Value));
                //((LineSeriesView)chartControl1.SeriesTemplate.View).LineMarkerOptions.Kind = MarkerKind.Square;
                //((LineSeriesView)chartControl1.SeriesTemplate.View).LineStyle.DashStyle = DashStyle.Dash;

                //            chartControl1.CustomDrawSeries += new CustomDrawSeriesEventHandler(chartControl1_CustomDrawSeries);


 * 
 * 
 *          //Type type = gvDaily.GetType();
            //FieldInfo fi = type.GetField("fViewInfo", BindingFlags.NonPublic | BindingFlags.Instance);
            //GridViewInfo info = fi.GetValue(gridView1) as GridViewInfo;
            //fi = type.GetField("fScrollInfo", BindingFlags.NonPublic | BindingFlags.Instance);

*/

// GridView Export : Progress
//link.Progress += new DevExpress.XtraGrid.Export.ProgressEventHandler(Export_Progress);

//        private void Export_Progress(object sender, DevExpress.XtraGrid.Export.ProgressEventArgs e)
//        {
//            //if (e.Phase == DevExpress.XtraGrid.Export.ExportPhase.Link)
//            //{
//            //    progressBarControl1.Position = e.Position;
//            //    this.Update();
//            //}
//        }
// link.Progress -= new DevExpress.XtraGrid.Export.ProgressEventHandler(Export_Progress);

//private void ExportTo(IExportProvider provider)
//        {
//            // ExportTo(new ExportXlsProvider(fileName));
//            using (DevExpress.Utils.WaitDialogForm waitDialog = new DevExpress.Utils.WaitDialogForm("Aktarılıyor!", "Lütfen Bekleyiniz."))
//            {
//                Cursor currentCursor = Cursor.Current;
//                Cursor.Current = Cursors.WaitCursor;

//                GridView.GridControl.FindForm().Refresh();
//                BaseExportLink link = GridView.CreateExportLink(provider);
//                (link as GridViewExportLink).ExpandAll = false;                
//                link.ExportTo(true);
//                provider.Dispose();
//                Cursor.Current = currentCursor;
//            }
//        }


//private bool USCanada(GridView view, int row)
//{
//    GridColumn col = view.Columns["Country"];
//    string val = Convert.ToString(view.GetRowCellValue(row, col));
//    return (val == "USA" || val == "Canada");
//}



//void tabAna_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
//{
//    if (e.Page == tpEkle && buttonEdit1.Text == string.Empty)
//        XtraMessageBox.Show("Yeni talep satırları girmek için, önce diğer sekmeden bir sipariş numarasına çift tıklamalısınız.", "Alert", MessageBoxButtons.OK);
//}


//sel[j++] = (int)gvEkle.GetRowCellValue(rowHandle, "idx");
//ds.xKstEkle.Clear();
//foreach (int val in sel)
//{

//    ConfExpert.Datasets.MyData.xKstEkleRow r = ds.xKstEkle.NewxKstEkleRow();
//    r.idx = val;
//    ds.xKstEkle.AddxKstEkleRow(r);
//}
//string serEkle = XML.Serialize(ds.xKstEkle);
//ds.xKstEkle.Clear();
//return serEkle;





//GridLookUpEdit gle = new GridLookUpEdit();
//gle.Size = gleGrup.Size;
//gle.Location = gleGrup.Location;
//gle.EditValueChanged += new EventHandler(gleGrup_EditValueChanged);

//RepositoryItemGridLookUpEdit riGrup = new RepositoryItemGridLookUpEdit();
//InitRepositoryItemGridLookUpEdit(riGrup, ds.xKstGrup, "ConfirmDate", "idx");
//riGrup.View.Columns["ConfirmDate"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
//riGrup.View.Columns["ConfirmDate"].DisplayFormat.FormatString = "g"; //G


//BindingSource bsx = new BindingSource(ds, "xKstGrup");
//bsx.Filter = "UreticiId = " + ureticiId;
//riGrup.DataSource = bsx;
//riGrup.View.Columns["UreticiId"].Visible = false;
//riGrup.View.Columns["Yukleme"].ColumnEdit = RI(Rp.YuklemeSekli);
//gle.Properties.Assign(riGrup);
//gle.EditValue = riGrup.View.GetDataRow(0)["idx"];

//int yukleme;
//DateTime kumastermini;
//private void gleGrup_EditValueChanged(object sender, EventArgs e)
//{
//    //gleGrup.Parent.Controls["btn"].Enabled = true;
//    GridLookUpEdit gleSender = (GridLookUpEdit)sender;
//    DataRow row = gleSender.Properties.View.GetDataRow(gleSender.Properties.View.FocusedRowHandle);
//    confirmDate = (DateTime)row["ConfirmDate"];
//    kumastermini = (row["KumasTermini"] == DBNull.Value ? new DateTime(2000, 1, 1) : (DateTime)row["KumasTermini"]);
//    yukleme = (row["Yukleme"] == DBNull.Value ? 0 : (int)row["Yukleme"]);
//}


//int UreticiId = (gleUretici.EditValue != null ? (int)gleUretici.EditValue : 0);
//int PaymentMethodId = (glePaymentMethod.EditValue != null ? (int)glePaymentMethod.EditValue : 0);
//int PaymentTermId = (glePaymentTerm.EditValue != null ? (int)glePaymentTerm.EditValue : 0);
//string SipNo = gleSipNo.EditValue.ToString();
//string UreticiSipNo = teUreticiSipNo.Text;
//int MarkaId = (gleMarka.EditValue != null ? (int)gleMarka.EditValue : 0);
//int TeslimSekliId = (gleTeslimSekli.EditValue != null ? (int)gleTeslimSekli.EditValue : 0);
//int YuklemeSekliId = (gleYuklemeSekli.EditValue != null ? (int)gleYuklemeSekli.EditValue : 0);
//DateTime Termin = (deTermin.EditValue != null ? (DateTime)deTermin.EditValue : new DateTime(2000, 1, 1));
////int Sezon = (gleSezon.EditValue != null ? (int)gleSezon.EditValue : 0);
//string Sezon = teSezon.Text;
//DateTime GomlekTermini = (deGomlekTermini.EditValue != null ? (DateTime)deGomlekTermini.EditValue : new DateTime(2000, 1, 1));

//Excelden oku
/*
OleDbConnection baglanti = new OleDbConnection("Data Source=deneme.xls;Provider=Microsoft.jet.OLEDB.4.0;Extended Properties=Excel 8.0");
OleDbConnection baglanti = new OleDbConnection("Data Source=deneme.xlsx;Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=Excel 12.0");
string aksesuarlar = "ROBA ETİKETİ;2 ETİKET;3 ETİKET;4 ETİKET;APARTURA ETİKETİ;MANŞET ETİKETİ;PAT ETİKETİ;DÜĞME ETİKETİ;YIKAMA TALİMATI ;HANG TAG;PELUR ÇEŞİDİ;PELUR;KATLAMA KARTONU;KELEBEK;ÇEMBER;YAKA ALTI;YAKA İÇİ;BALEN;ASKOLİT;BEDEN ETİKETİ;DÜĞME RENGİ;DÜĞME İPİ RENGİ;İLİK RENGİ;DÜĞME ÇEŞİDİ;GÖĞÜS ŞERİDİ ;KULLANILMASI GEREKEN ;DÜĞME 24 BOY;DÜĞME 20 BOY;DÜĞME 18 BOY;DÜĞME 16 BOY;DÜĞME 14 BOY;ÇIT ÇIT1;ÇIT ÇIT1 ADEDİ;ÇIT ÇIT 2;ÇITÇIT2 ADEDİ;BÖCEK ETİKETİ;BÖCEK ETİKETİ ADEDİ ;CEP ETİKETİ;KOL DÜĞMESİ;KOL DÜĞMESİ ADEDİ;YAKA TELASI ;KUŞAK TELASI;MANŞET TELASI;PAT TELASI;APOLET TELASI ;CEP KAPAĞI TELASI ;POLİGOT TELASI ;JELATİN";
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=WorksheetName;Extended Properties=""Excel 12.0 Xml;HDR=NO;""";

 * /*
        What provider do you use when accessing an Access 2007 database in a 64-bit windows machine? 

        You can use the 32-bit provider as long as your app is compiled as a 32-bit process. If you're 
        working with .NET you would need to select the x86 compile option. 

//dt.Locale = new CultureInfo("tr-TR"); // ","
                        //mySheet = System.IO.Path.GetFileName(fileName).Replace(".XLS", "");



 * 
 *  public static DataTable Xml2Sp(string StoredProcedureName, StringWriter sw, params object[] opt)
        {
            DataTable dt = new DataTable();

            using (SqlConnection baglanti = new SqlConnection(SqlConnectionString))
            {
                try
                {
                    baglanti.Open();
                    SqlCommand komut = new SqlCommand(StoredProcedureName, baglanti);
                    komut.CommandTimeout = 0;
                    komut.CommandType = CommandType.StoredProcedure;
                    if (StoredProcedureName == "ImportSO")
                    {
                        komut.Parameters.Add(new SqlParameter("@BrandId", 1));
                        komut.Parameters.Add(new SqlParameter("@SezonId", 2));
                    }

                    komut.Parameters.Add(new SqlParameter("@xmlstr", sw.ToString()));
                    //komut.Parameters.Add(new SqlParameter("@pass", pass));
                    //komut.Parameters.Add(new SqlParameter("@sheetName", sheetName));

                    SqlDataReader oku = komut.ExecuteReader();
                    dt.Load(oku);
                }
                catch (Exception Ex)
                {
                    string Message = Ex.Message;
                }
                finally
                {
                    baglanti.Close();
                }
            }
            return dt;
        } 
 * 
 * 
 * 
 * 
 * 
 *     static void cmdImport_Click(object sender, EventArgs e)
        {
            string sSourceConstr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\AgentList.xls; Extended Properties=""Excel 8.0;HDR=YES;""";
            string sDestConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
            using (sSourceConnection)
            {
                string sql = string.Format("Select [MSISDN],[Name],[Company],[Status] FROM [{0}]", "Sheet1$");
                OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
                sSourceConnection.Open();
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sDestConstr))
                    {
                        bulkCopy.DestinationTableName = "tblAgent";
                        //You can mannualy set the column mapping by the following way.
                        //bulkCopy.ColumnMappings.Add("MSISDN", "MSISDN");
                        bulkCopy.WriteToServer(dr);
                    }
                }
            }
        }
        */



//public static DataTable AddStringBooleanColumn(DataTable SourceTable, string ColumnToChange, string TrueText, string FalseText)
//{
//    string tempColName = "Message" + ColumnToChange;
//    SourceTable.Columns.Add(tempColName, typeof(string));
//    bool val;
//    foreach (DataRow row in SourceTable.Rows)
//    {
//        val = (bool)row[ColumnToChange];
//        if (val)
//        {
//            row[ColumnToChange] = TrueText;
//        }
//        else
//        {
//            row[ColumnToChange] = FalseText;
//        }
//    }
//    return SourceTable;
//}

/*
            //Create the serializer
            XmlSerializer slz = new XmlSerializer(someType);

            //Serialize the object with our own namespaces (notice the overload)
            slz.Serialize(myXmlTextWriter, someObject, ns);
*/
//StringWriter sw = new StringWriter();
/*
// now, serialize the object
XmlSerializer xmlr = new XmlSerializer(typeof(Docs));
StringWriter sw = new StringWriter();
XmlTextWriter tw = new MyXmlTextWriter(sw);
xmlr.Serialize(tw, docs, ns);
MessageBox.Show(sw.ToString());
             
//For deserialization we have: 
// Deserializing the object
StringReader sr = new StringReader(sw.ToString());
Docs docs2 = (Docs) xmlr.Deserialize(sr);
MessageBox.Show(docs2.ToString());
*/



//            System.IO.FileStream fileStream;
//            byte[] fileData;
//            fileStream = new System.IO.FileStream(this.OpenFileDialog.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
//            fileData = new byte[(int)fileStream.Length];
//            fileStream.Read(fileData, 0, (int)fileStream.Length);



//private void btnCopy_Click(object sender, EventArgs e)
//{
//    if (gvInitialCounting.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
//    {
//        copiedRow = (int)gvInitialCounting.GetRowCellValue(gvInitialCounting.FocusedRowHandle, "RollId");
//        btnCopy.Tag = gvInitialCounting.FocusedRowHandle;
//        btnCopy.Text = "Kopyala : " + copiedRow.ToString();
//    }
//}

//private void btnPaste_Click(object sender, EventArgs e)
//{
//    if (gvInitialCounting.SelectedRowsCount > 0 && ccmbAlanlar.EditValue != null && btnCopy.Tag!=null)
//    {
//        foreach (string fldx in ccmbAlanlar.EditValue.ToString().Split(';'))
//        {
//            string fld = fldx.Trim();
//            object val = gvInitialCounting.GetRowCellValue((int)btnCopy.Tag, fld);
//            for (int i = 0; i < gvInitialCounting.SelectedRowsCount; i++)
//            {
//                DataRow row = gvInitialCounting.GetDataRow(gvInitialCounting.GetSelectedRows()[i]);
//                if (val != null)
//                    row[fld] = val;
//                else
//                    row[fld] = DBNull.Value;
//            }
//        }
//    }
//}

//private void btnCopyProduct_Click(object sender, EventArgs e)
//{
//    if (gridView1.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
//    {
//        copiedRow = (int)gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ProductId");
//        btnCopyProduct.Tag = gridView1.FocusedRowHandle;
//        btnCopyProduct.Text = "Kopyala : " + copiedRow.ToString();
//    }
//}

//private void btnPasteProduct_Click(object sender, EventArgs e)
//{
//    if (gridView1.SelectedRowsCount > 0 && ccmbProduct.EditValue != null && btnCopyProduct.Tag != null)
//    {
//        foreach (string fldx in ccmbProduct.EditValue.ToString().Split(';'))
//        {
//            string fld = fldx.Trim();
//            object val = gridView1.GetRowCellValue((int)btnCopyProduct.Tag, fld);
//            for (int i = 0; i < gridView1.SelectedRowsCount; i++)
//            {
//                DataRow row = gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
//                if (val != null)
//                    row[fld] = val;
//                else
//                    row[fld] = DBNull.Value;
//            }
//        }
//    }
//}


//        using (Product search = new Product(st, true))
//        {
//            search.StartPosition = FormStartPosition.CenterParent;
//            search.ShowDialog();


//if (searchmode)
//{
//    StringBuilder Fltr = new StringBuilder();
//    foreach (GridView gv in gvs)
//        if (gv.ActiveFilter.Expression != String.Empty)
//            Fltr.Append((Fltr.Length > 0 ? " AND " : "") + gv.ActiveFilter.Expression);
//    AF_Product = Fltr.ToString();
//    this.Close();


//void ActiveFilter_Changed(object sender, EventArgs e)
//{
//    if (!Equals(gvProductBase.Columns["ProductCategoryId"].FilterInfo.FilterCriteria, null))
//    {
//        int ProductCategoryId = int.Parse(((DevExpress.Data.Filtering.BinaryOperator)(gvProductBase.Columns["ProductCategoryId"].FilterInfo.FilterCriteria)).RightOperand.ToString());
//        ArrangeFeatureGrid(ProductCategoryId);
//    }
//}

//void gvList_DoubleClick(object sender, EventArgs e)
//{
//    int ProductBaseId = intParse(bsList, "ProductBaseId");
//    try
//    {
//        GetDetails("ProductBase;ProductFeature;ProductPhoto;Product", "A04", 2, st, ProductBaseId, null);

//        gvProductBase.UnselectRow(gvProductBase.FocusedRowHandle);
//        //bu ArrangeFeatureGrid() i tetikliyor!
//        gvProductBase.FocusedRowHandle = gvProductBase.LocateByValue(0, gvProductBase.Columns["ProductBaseId"], ProductBaseId);
//        gvProductBase.SelectRow(gvProductBase.FocusedRowHandle);

//    }
//    finally
//    {
//        //suspendPBCC = false;
//    } 
//}

//void bsTalepLines_CurrentChanged(object sender, EventArgs e)
//{
//    //newItemRow satırı olmasın!
//    if (bsTalepLines != null)
//        bsTalepLines.Filter = "TalepId = " + intParse(bsTalepLines, "TalepId");
//    else
//        bsTalepLines.Filter = "TalepId = -1";
//}

//converting the image to Bitmap.
//
//OpenFileDialog dlg = new OpenFileDialog();
// if(dlg.ShowDialog() == DialogResult.OK) {
//     Image img = Image.FromFile(dlg.FileName);
//     System.IO.MemoryStream s = new System.IO.MemoryStream();
//     img.Save(s, img.RawFormat); <- ERR
//     byte[] ret = s.ToArray();
//     s.Close();
//} 
//

//                GetDetails("xProductList;xInitialCountingK;Talep;TalepLines;TalepLinesSatinalma;xSatinalma;TalepLinesRezerve;xRezerve;TalepLinesUsage", "A04", st, 1);
//GetDetails("xProductList;xInitialCountingK;Talep;TalepLines", "A04", 1, st, null, null);


/*
dataNavigator1.DataSource = bsProductBase;
InitDataLayoutControl(dataLayoutControl1, bsProductBase);
dataLayoutControl1.OptionsView.HighlightFocusedItem = true;
StokkoduTipiIdLookUpEdit.Properties.Assign(riStokkoduTipi);
StokTipiIdLookUpEdit.Properties.Assign(riStokTipi);
UserIdGridLookUpEdit.Properties.Assign(riEmployee);
ProductCategoryIdGridLookUpEdit.Properties.Assign(riProductCategory);
UnitMeasureIdLookUpEdit.Properties.Assign(riUnitMeasure);

InitGridView(gridView1, bsProduct);
gridView1.Columns["ProductId"].Visible = false;
gridView1.Columns["ProductBaseId"].Visible = false;
//gridView1.OptionsView.ShowIndicator = false;
gridView1.InitNewRow += new DevExpress.XtraGrid.Views.Grid.InitNewRowEventHandler(gvProduct_InitNewRow);
*/


//gvProductBase.ActiveFilter.Changed += new EventHandler(ActiveFilter_Changed);


//if (searchmode)
//{
//    btnScan.Visible = false;
//    dataNavigator1.Enabled = false;
//    foreach (GridView gv in gvs)
//    {
//        gv.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
//        gv.OptionsView.ShowAutoFilterRow = true;
//    }
//}
//else




//private void btnCopyK_Click(object sender, EventArgs e)
//{
//    if (gvRoll2.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
//    {
//        int copiedRow = (int)gvRoll2.GetRowCellValue(gvRoll2.FocusedRowHandle, "RollId");
//        btnCopyK.Tag = gvRoll2.FocusedRowHandle;
//        btnCopyK.Text = "Kopyala : " + copiedRow.ToString();
//    }
//}

//private void btnPasteK_Click(object sender, EventArgs e)
//{
//    if (gvRoll2.SelectedRowsCount > 0 && ccmbK.EditValue != null && btnCopyK.Tag != null)
//    {
//        foreach (string fldx in ccmbK.EditValue.ToString().Split(';'))
//        {
//            string fld = fldx.Trim();
//            object val = gvRoll2.GetRowCellValue((int)btnCopyK.Tag, fld);
//            for (int i = 0; i < gvRoll2.SelectedRowsCount; i++)
//            {
//                DataRow row = gvRoll2.GetDataRow(gvRoll2.GetSelectedRows()[i]);
//                if (val != null)
//                    row[fld] = val;
//                else
//                    row[fld] = DBNull.Value;
//            }
//        }
//    }
//}

//DataTable dt = new DataTable();
//dt.Columns.Add("GelisPartisiId", typeof(int));
//foreach (object item in gvGelisPartisi.sel.SelectedItems)
//{
//    int res = intParse(item);
//    if (res > 0)
//        liste += res.ToString() + ",";
//    //dt.Rows.Add(res);
//}
//Barcode barcode = new Barcode(XmlSerialize(dt), etikettip.GelisPartisiId);

//string[] itemValuesProduct = "MDepoId;DepoId;ShelfId".Split(';');
//foreach (string value in itemValuesProduct)
//    ccmbK.Properties.Items.Add(value, CheckState.Unchecked, true);
//ccmbK.Properties.SeparatorChar = ';';
//ccmbK.SetEditValue("MDepoId;DepoId;ShelfId");


//private void btnCopyA_Click(object sender, EventArgs e)
//{
//    if (gv1.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
//    {
//        int copiedRow = (int)gv1.GetRowCellValue(gv1.FocusedRowHandle, "ProductId");
//        btnCopy.Tag = gv1.FocusedRowHandle;
//        btnCopy.Text = "Kopyala : " + copiedRow.ToString();
//    }
//}

//private void btnPasteA_Click(object sender, EventArgs e)
//{
//    if (gv1.SelectedRowsCount > 0 && ccmb.EditValue != null && btnCopy.Tag != null)
//    {
//        foreach (string fldx in ccmb.EditValue.ToString().Split(';'))
//        {
//            string fld = fldx.Trim();
//            object val = gv1.GetRowCellValue((int)btnCopy.Tag, fld);
//            for (int i = 0; i < gv1.SelectedRowsCount; i++)
//            {
//                DataRow row = gv1.GetDataRow(gv1.GetSelectedRows()[i]);
//                if (val != null)
//                    row[fld] = val;
//                else
//                    row[fld] = DBNull.Value;
//            }
//        }
//    }
//}

//string[] itemValuesProduct = "Y_ShelfId;QtyEDITED".Split(';');
//foreach (string value in itemValuesProduct)
//{
//    ccmb.Properties.Items.Add(value, CheckState.Unchecked, true);
//}
//ccmb.Properties.SeparatorChar = ';';
//ccmb.SetEditValue("Y_ShelfId");

//void bsTalepLines_CurrentChanged(object sender, EventArgs e)
//{
//ExpandCollapse(scSonuc, bsTalepLines2.Current != null ? AcKapa.Expand : AcKapa.Collapse);
////            ExpandCollapse(scSonuc, ((DataRowView)bsTalepLines2.Current).DataView.Count > 0 ? AcKapa.Expand : AcKapa.Collapse);
//}

//private DevExpress.XtraBars.PopupMenu pmXtl2;

//void gvxTalepLines2_ShowGridMenu(object sender, GridMenuEventArgs e)
//{
//    if (e.Menu == null || e.Menu.GetType() == typeof(DevExpress.XtraGrid.Menu.GridViewMenu))
//        pmXtl2.ShowPopup((sender as GridView).GridControl.PointToScreen(e.Point));
//}

//if (BrandId < 0)
//{
//    MessageBox.Show("Marka girmediniz!", "Warning", MessageBoxButtons.OK);
//    return;
//}

//lblProc.Text = "Yeni Talep - " + AppSession.Lookups.Brand.FindByBrandId(BrandId).Name;



//StokTipi st = StokTipi.Kumas;
//public StokKartiA(FormType ft)
//{
//    InitializeComponent();
//    st = (ft == FormType.Aksesuar ? StokTipi.Aksesuar : StokTipi.Kumas);
//}


//namespace ConfExpert.Planlama
//{
//    public partial class YeniTalepA : YeniTalep
//    {
//        public YeniTalepA()
//        {
//            InitializeComponent();
//            SetType(StokTipi.Aksesuar);
//        }

//        private void YeniTalepA_Load(object sender, EventArgs e)
//        {

//            GridManager.Initialize(Enums.FormId.YeniTalepA,
//                new GridView[] { gvAvail, gvxTalepLines, gvxTalepLines2 },
//                new BindingSource[] { bsAvail, bsxTalepLines, bsxTalepLines2 });

//            SetMode();

//        }

//    }
//}

/*
//I am using WIA 2.0 to acquire scan from a scanner in my c# application as follows:  
CommonDialogClass wiaDlg = new CommonDialogClass();  
ImageFile imfile = wiaDlg.ShowAcquireImage(WiaDeviceType.ScannerDeviceType, WiaImageIntent.TextIntent, WiaImageBias.MinimizeSize, FormatID.wiaFormatPNG, false, true, false);  
  */

//void btnEtiket_Click(object sender, EventArgs e)
//{
//    using (ConfExpert.Depo.A04_Barcode_Range br = new ConfExpert.Depo.A04_Barcode_Range())
//    {
//        if (br.ShowDialog() == DialogResult.OK)
//        {
//            ConfExpert.Depo.Barcode barcode = new ConfExpert.Depo.Barcode(br.BarcodeRange, etikettipi.RollId);
//            barcode.ShowPreviewDialog();
//        }
//    }


//}


//private void DisplayKnownColors(PaintEventArgs e)
//{
//    this.Size = new Size(650, 550);

//    // Get all the values from the KnownColor enumeration.
//    System.Array colorsArray = Enum.GetValues(typeof(KnownColor));
//    KnownColor[] allColors = new KnownColor[colorsArray.Length];

//    Array.Copy(colorsArray, allColors, colorsArray.Length);

//    // Loop through printing out the values' names in the colors 
//    // they represent.
//    float ilkAyrim = 0;
//    float x = 10.0F;

//    for (int i = 0; i < allColors.Length; i++)
//    {

//        // If x is a multiple of 30, start a new column.
//        if (i > 0 && i % 30 == 0)
//        {
//            x += 105.0F;
//            ilkAyrim = 15.0F;
//        }
//        else
//        {
//            // Otherwise, increment ilkAyrim by 15.
//            ilkAyrim += 15.0F;
//        }

//        // Create a custom brush from the color and use it to draw
//        // the brush's name.
//        SolidBrush aBrush =
//            new SolidBrush(Color.FromName(allColors[i].ToString()));
//        e.Graphics.DrawString(allColors[i].ToString(),
//            this.Font, aBrush, x, ilkAyrim);

//        // Dispose of the custom brush.
//        aBrush.Dispose();
//    }

//}


//GridViewInfo viewInfo = gvProductFeature.GetViewInfo() as GridViewInfo;
//int viewHeight = viewInfo.CalcRealViewHeight(new Rectangle(0, 0, gcProductFeature.Width, 200));
//splitContainerControl2.SplitterPosition = 2 * viewHeight + 0;
//gcProductBase.Height = viewHeight;


//gvProduct.FocusedRowHandle = gvProduct.LocateByDisplayText(0, gvProduct.Columns["Renk"], R);
//gvProduct.MakeRowVisible(gvProduct.FocusedRowHandle, true);

//gvKstOzet.MoveLast();
//gvKstOzet.TopRowIndex = gvKstOzet.FocusedRowHandle;
//gvKstOzet.MakeRowVisible(gvKstOzet.FocusedRowHandle, true);



//    pictureEdit1.DataBindings.Add("EditValue", bsProductPhoto, chkSize.Checked ? "BLOBMini" : "BLOB");



/*
private void UpdatePrice(DevExpress.XtraGrid.Views.Base.ColumnView View) {
  DevExpress.XtraGrid.Columns.GridColumn col = View.Columns.ColumnByFieldName("Price");
  if (col == null) return;
  View.BeginSort();
  try {
     int dataRowCount = View.DataRowCount;
     for (int i = 0; i < dataRowCount; i++) {
        object cellValue = View.GetRowCellValue(i, col);
        double newValue = Convert.ToDouble(cellValue) * 0.9;
        View.SetRowCellValue(i, col, newValue);
     }
  } finally { View.EndSort(); 
}
}


for (int i = 0; i < 10; i++)
{
Console.WriteLine(i.ToString() + ": " + 
gridView1.GetVisibleRowHandle(i).ToString() + ": " + 
gridView1.IsRowVisible(gridView1.GetVisibleRowHandle(i)));
// r = gridView1.GetNextVisibleRow(r);
}
Console.WriteLine(gridView1.TopRowIndex);





string splitme = "foo,bar,feet,meet,meat,skeet";
ArrayList gatherSplit = new ArrayList(splitme.Split(','));

 

 * 
 * 

        void bsProductBase_CurrentChanged(object sender, EventArgs e)
        {
            if (bsProductBase.Current != null)
            {
                //gvProductBase.Columns["ProductCategoryId"].OptionsColumn.ReadOnly = gvProductBase.Columns["StokkoduTipiId"].OptionsColumn.ReadOnly = int.Parse(((DataRowView)bsProductBase.Current).Row["ProductBaseId"].ToString()) > 0;
                int ProductCategoryId = intParse(bsProductBase, "ProductCategoryId");
                ArrangeFeatureGrid(ProductCategoryId);
                gvProduct.BestFitColumns();
            }
        }

        void bsPFK_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                gvProductFeature.OptionsView.NewItemRowPosition = bsPFK.Position > -1 ? NewItemRowPosition.None : NewItemRowPosition.Top;
                gvProductFeature.BestFitColumns();
            }
            catch (Exception)
            {
            }
        }

        private void ArrangeFeatureGrid(int ProductCategoryId)
        {
            for (int i = 0; i < AppSession.Lookups.Feature.Rows.Count; i++)
                if (AppSession.Lookups.Feature[i].Scope == "F")
                    if (AppSession.Lookups.Feature[i].StokTipiId == 1) //Kumaş ve Feature verisi
                    {
                        GridColumn col = gvProductFeature.Columns[CatAbbr(i)];
                        col.Caption = CatName(i);
                        col.VisibleIndex = i;

                        FilteredLookUp(ProductCategoryId, i, col);
                    }
            bsPFK.EndEdit();
            gvProductFeature.BestFitColumns();
            FilteredLookUp(ProductCategoryId, 1, gvProduct.Columns["Boy"]);
        }

        int Flag(int cId)
        {
            return (int)AppSession.Lookups.ProductCategory.Rows.Find(cId)["ApplicableFeatures"];
            //return (int)AppSession.Lookups.ProductCategory.FindByProductCategoryId(cId)["ApplicableFeatures"];
        }

        string CatName(int i)
        {
            return AppSession.Lookups.Feature[i].Name;
        }

        string CatAbbr(int i)
        {
            return AppSession.Lookups.Feature[i].Abbr;
        }

        private void FilteredLookUp(int ProductCategoryId, int FeatureId, GridColumn col)
        {
            DataView clone = new DataView(AppSession.Lookups.Joker);
            clone.RowFilter = "ProductCategoryId=" + ProductCategoryId.ToString() + " AND FeatureId=" + FeatureId.ToString() + " AND ISNULL(Deleted, 0) = 0";
            try
            {
                if (clone.Count > 0)
                {
                    RepositoryItemLookUpEdit rep = RI(Rp.Joker).Clone() as RepositoryItemLookUpEdit;
                    rep.DataSource = clone;
                    col.ColumnEdit = rep;
                }
                //else if (col.Caption == "Marka")
                //    col.ColumnEdit = RI(Rp.Brand);
                else if (col.Caption == "Kalite")
                    col.ColumnEdit = RI(Rp.Kalite);
                else if (col.Caption == "O.Uretici")
                    col.ColumnEdit = RI(Rp.V_Vendor);   //bunların valuemember - displaymember ları uyuşmuyor!
                //engrubunu joker de tanımla!
                else
                    col.ColumnEdit = null;

            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }

        void riProductCategory_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {

            if ((sender as BaseEdit).Parent.Name.Contains("ProductBase"))
                ArrangeFeatureGrid(int.Parse(e.NewValue.ToString()));

            //gvProductBase.FocusedColumn = gvProductBase.Columns["Adet"];
            //ConfExpert.Datasets.MyData.V_AksesuarRow pRow = dsi.V_Aksesuar.FindByProductId(int.Parse(gvAFLK.GetRowCellValue(gvAFLK.FocusedRowHandle, "ProductId").ToString()));
            //gvAFLK.SetRowCellValue(gvAFLK.FocusedRowHandle, "ProductCategoryId", pRow.ProductCategoryId);
        }
 * 

 * 
 * 
 * 
 * 
 * 
using System; using DevTeam;
using DevTeam;
using System.Data;
using System.Data.Common;
using System.Windows.Forms;
using ConfExpert.Datasets;

using ConfExpert.Forms.Base;
using ConfExpert.Utility;

using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

namespace ConfExpert.Forms.Depo
{
    public partial class TopBolme : XFormWithBar
    {
        int rollId;
        decimal initialQty;

        public TopBolme(int rollId)
        {
            InitializeComponent();
            this.rollId = rollId;
        }

        BindingSource bs;
        private void BindData()
        {
            //gcRoll.DataSource = ds.Roll;
            bs = new BindingSource(ds, "Roll");
            GridManager.Initialize(Enums.FormId.TopBolme,
                new GridView[] { gvRoll },
                new BindingSource[] { bs });

            DbCommand cmd = Session.DataManager.GetSqlStringCommand("select * from Roll where RollId=" + rollId);
            DataRow dr = Session.DataManager.ExecuteDatarow(cmd);

            if (dr == null)
                this.DialogResult = DialogResult.Cancel;

            gvRoll.Columns["InitialQty"].Width = 64;
            initialQty = (decimal)dr["InitialQty"];
            lbl.Text = "RollId: " + dr["RollId"].ToString() + ". InitialQty: " + Numeric2(initialQty);
        }

        private void TopBolme_Load(object sender, EventArgs e)
        {
            barMain.AddItem(bbiKaydet);
            BindData();
        }



        private void bbiKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvRoll.CloseEditor();
            gvRoll.UpdateCurrentRow();

            decimal fark = CheckRolls();

            if (fark == 0)
            {
                if (XtraMessageBox.Show("Topların bölündükten sonra tekrar birleştirilmesi mümkün olmayacaktır. Bölmek istediğinizden EMİN MİSİNİZ?", "DİKKAT", MessageBoxButtons.YesNo) == DialogResult.No)
                    this.DialogResult = DialogResult.Cancel;
                else
                {
                    ExecQuery("UpdRollSplitMultiple", rollId, WhoAmI, XML.SerializeAll(ds.Roll));
                    this.DialogResult = DialogResult.Yes;
                }
            }
            else if (fark > 0)
            {
                if (XtraMessageBox.Show(LookAndFeel.ActiveLookAndFeel, "Toplam uzunluk, o artikel için girilen miktarın altında. Arta kalan kısmı ayrı bir top olarak ayırmak ister misiniz?", "Uyarı", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (XtraMessageBox.Show("Topların bölündükten sonra tekrar birleştirilmesi mümkün olmayacaktır. Bölmek istediğinizden EMİN MİSİNİZ?", "DİKKAT", MessageBoxButtons.YesNo) == DialogResult.No)
                        this.DialogResult = DialogResult.Cancel;
                    else
                    {
                        decimal qty = (decimal)ds.Roll.Compute("Sum(InitialQty)", string.Empty);

                        ConfExpert.Datasets.MyData.RollRow dr = ds.Roll.NewRollRow();
                        dr.Qty = initialQty - qty;
                        ds.Roll.Rows.Add(dr);

                        ExecQuery("UpdRollSplitMultiple", rollId, WhoAmI, XML.SerializeAll(ds.Roll));
                        this.DialogResult = DialogResult.Yes;
                    }
                }
            }
            else if (fark < 0)
            {
                XtraMessageBox.Show(LookAndFeel.ActiveLookAndFeel, "Toplam uzunluk, o artikel için girilen miktarı aşamaz. Girdiğiniz miktarları düzelttikten sonra kaydetmeyi deneyiniz.", "Uyarı", MessageBoxButtons.OK);
            }
        }

        private MyData.xRollReserveDataTable data = new MyData.xRollReserveDataTable();
        public MyData.xRollReserveDataTable Data
        {
            get { return data; }
        }

        private decimal CheckRolls()
        {
            return initialQty - (decimal)ds.Roll.Compute("Sum(InitialQty)", string.Empty);
        }
    }
}





        void gvRoll_HiddenEditor(object sender, EventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view;
            view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            DataRow rowTL = view.GetDataRow(view.FocusedRowHandle);
            GridColumn col = view.FocusedColumn;
            if (rowTL != null)
                if (col.FieldName.Contains("Qty"))
                {
                    col.ColumnEdit = new RepositoryItemProgressBar();
                    ((RepositoryItemProgressBar)col.ColumnEdit).ShowTitle = true;
                    ((RepositoryItemProgressBar)col.ColumnEdit).PercentView = false;
                    ((RepositoryItemProgressBar)col.ColumnEdit).Maximum = 700;
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    col.DisplayFormat.FormatString = "#,###.##";
                }
        }

        void gvRoll_ShownEditor(object sender, EventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view;
            view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
            DataRow rowTL = view.GetDataRow(view.FocusedRowHandle);
            GridColumn col = view.FocusedColumn;
            if (rowTL != null)
                if (col.FieldName.Contains("Qty"))
                {
                    col.ColumnEdit = null;
                    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
                    col.DisplayFormat.FormatString = "#,###.##";
                }
        }
 * 
 * 

        void TopluTalep()
        {
            using (Automation auto = new Automation(1))
            {
                if (auto.ShowDialog() == DialogResult.OK)
                {
                    string FileName = auto.FileName;

                    GetDetails("xTopluBrands;xTopluNeed", "TopluTalep", DataManager.Datatable2Xml(DataManager.XlsToDatatable(FileName)).ToString(), st);
                    //ds.xTopluBrands.Columns.Add("DateSubmitted", typeof(DateTime));
                    //tpToplu.Text = "Toplu - " + ds.xTopluBrands.Compute("COUNT(BrandId)", "DateSubmitted is null");

                    bsTopluBrands = new BindingSource(ds, "xTopluBrands");
                    bsTopluNeed = new BindingSource(bsTopluBrands, "FK_xTopluNeed_xTopluBrands_BrandId");
                    InitLookUp(leToplu, bsTopluBrands, "BrandId", "Brand");
                    //bsTopluBrands.MoveFirst();
                    //bsTopluBrands.EndEdit();
                    //InitGridView(gvToplu, bsTopluBrands);
                    //gvToplu.OptionsBehavior.Editable = false;
                    cbShowOnly.Text = "HEPSİ";  //EditValue
                    topluInUse = true;
                }
            }
        }
 * 

        private void btnTopluTalep_Click(object sender, EventArgs e)
        {
            try
            {
                topluInUse = true;
                string FileName = string.Empty;
                using (Automation auto = new Automation(1))
                {
                    if (auto.ShowDialog() == DialogResult.OK)
                    {
                        FileName = auto.FileName;

                        //DataSet ds = new DataSet();
                        //dt = ExcelOku.Xml2Sp("TopluTalep", DataManager.Datatable2Xml(DataManager.XlsToDatatable(FileName)));
                        GetDetails("xTopluBrands;xTopluNeed", "TopluTalep", DataManager.Datatable2Xml(DataManager.XlsToDatatable(FileName)).ToString(), st);
                        bsTopluBrands = new BindingSource(ds, "xTopluBrands");
                        bsTopluNeed = new BindingSource(bsTopluBrands, "FK_xTopluNeed_xTopluBrands_BrandId");
                        InitGridView(gvToplu, bsTopluBrands);
                        gvToplu.OptionsBehavior.Editable = false;
                    }
                }

            }
            finally
            {
                topluInUse = false;
            }
        } * 
 
        void gvAvailDoubleClick(object sender, EventArgs e)
        {
            try
            {
                gvAvail.SetRowCellValue(gvAvail.FocusedRowHandle, "SEÇ", (gvAvail.GetRowCellDisplayText(gvAvail.FocusedRowHandle, "SEÇ") == "SEÇİLDİ") ? string.Empty : "SEÇİLDİ");
            }
            catch (Exception Ex)
            {
                throw(Ex);
            }
        }
 * 
 * 
         void RepositoryManager_ProcessGridKey(object sender, KeyEventArgs e)
        {
            GridView FocusedView = (sender as GridControl).MainView as GridView;
            if (e.KeyCode == Keys.Delete)
            {
                if (FocusedView.ActiveEditor == null) return;

                Object obj = FocusedView.ActiveEditor;

                //if (obj is LookUpEdit)
                //{
                //    LookUpEdit lkpEdit = this.FocusedView.ActiveEditor as LookUpEdit;
                //    if (lkpEdit != null && !lkpEdit.Properties.ReadOnly)
                //        lkpEdit.EditValue = null;
                //}
                //else if (obj is CheckedComboBoxEdit)
                //{
                //    CheckedComboBoxEdit comboEdit = this.FocusedView.ActiveEditor as CheckedComboBoxEdit;
                //    if (!comboEdit.Properties.ReadOnly)
                //    {
                //        comboEdit.SetEditValue(null);
                //    }
                //}
                //else 
                if (obj is GridLookUpEdit)
                {
                    GridLookUpEdit gridLookUpEdit = obj as GridLookUpEdit;
                    gridLookUpEdit.EditValue = null;
                }
            }
        }* 
* * 
 * 
 * 
for (int i = 0; i < gvToplar.DataRowCount; i++)
{
    DataRow dr = gvToplar.GetDataRow(i);
    if (dr["QtyAvailable"].ToString() != "")
    {
        dt.Rows.Add((int)dr["RollId"]);
        int AllocatedForId = intParse(dr["AllocatedForId"]);
        if (AllocatedForId > 1 && AllocatedForId != BrandId)
            izinal = true;
    }
}
 * 

}*
 * 
 * 
 
        private void Proceed()
        {
            switch (step)
            {
                case 0:     //Eksik kartların açılması ve girilen verinin TalepLines a yazılması

                    MapArticles();
                    string xml;
                    DataRow[] drs = ds.xTGTalep.Select("ProductId is NULL");

                    if (drs.Length > 0)
                        if (ShowWarningMessage(drs.Length + " adet kumaş için yeni kart açılacak, emin misiniz?") == DialogResult.Yes)
                        {
                            bsTalepLines.EndEdit();
                            xml = XML.SerializeAll(ds.xTGTalep);
                            ds.xTGTalep.Clear();
                            GetDetails("xTGTalep", "GetTalepLines", 1, talepId, WhoAmI, xml);
                            //eklenen kumaşlar, lookup ta çıksın diye!
                            AppSession.MainForm.RaiseUpdate(null, null);
                        }
                        else
                            return;                   

                    xml = XML.SerializeAll(ds.xTGTalep);
                    ds.xTGTalep.Clear();
                    GetDetails("xTGTalep", "GetTalepLines", 2, talepId, WhoAmI, xml);

                    break;
                case 1:

                    //MalSahibi != 1 olan PO ların oluşturulması ve işlemin bittiğini bildiren bilgi mesajı                
                    gvTalep.OptionsBehavior.AllowAddRows = gvTalep.OptionsBehavior.AllowDeleteRows = DefaultBoolean.False;
                    gvTalep.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
                    gvTalep.OptionsBehavior.Editable = false;

                    //bbiIlerle.Glyph = ConfExpert.Properties.Resources.stop_24;

                    SatinAlmaSiparisiOlustur();

                    ShowInfoMessage("Talep kaydedildi.");

                    break;

                case 2:
                    this.Close();
                    break;

            }

            gvTalep.BestFitColumns();
        } 


        private void gvTalep_DoubleClick(object sender, EventArgs e)
        {
            EndGridViewEdit(gvTalep);
            int rowHandle = gvTalep.FocusedRowHandle;
            if (rowHandle > -1)
            {
                if (intParse(gvTalep.GetFocusedRowCellValue("stTalepId")) == 4)
                    return;

                bool isTalepValid = IsTalepValid();

                if (isTalepValid)
                {
                    Kaydet();


                    int talepLinesId = intParse(gvTalep.GetFocusedRowCellValue("TalepLinesId"));
                    if (talepLinesId < 0)
                    {
                        DataTable dt = ds.xTGTalep.Select("TalepLinesId = " + talepLinesId).CopyToDataTable();
                        DataSet dsTalep = new DataSet();
                        dsTalep.DataSetName = ds.DataSetName;
                        dsTalep.Tables.Add(dt);

                        int newTalepLinesId = intParse(ExecQuery("InsertTalepLines", XML.SerializeTable(ds)));
                        ds.xTGTalep.FindByTalepLinesId(talepLinesId).TalepLinesId = newTalepLinesId;
                    }
                    int TalepLinesId = intParse(bsTalepLines, "TalepLinesId");
                    int BrandId = intParse(bsTalepLines, "BrandId");
                    int ProductId = intParse(bsTalepLines, "ProductId");
                    decimal QtyNeeded = decimalParse(bsTalepLines, "QtyNeeded");
                    Rezerve rezerve = new Rezerve(StokTipi.Kumas, TalepLinesId, BrandId, ProductId, QtyNeeded, ref bsTalepLines);
                    rezerve.ShowDialog();

                }
                else
                {
                    ShowErrorMessage("Lütfen işaretli alanları doldurunuz.");
                }

            }
        }
        * 

    RepositoryItemImageComboBox imageCombo = gv.GridControl.RepositoryItems.Add("ImageComboBoxEdit") as RepositoryItemImageComboBox;
    imageCombo.Items.BeginUpdate();
    int ndx = 0;
    imageCombo.SmallImages = ErrorOk;
    imageCombo.GlyphAlignment = DevExpress.Utils.HorzAlignment.Center;
    foreach (string opt in opts.Split('|'))
        imageCombo.Items.Add(new ImageComboBoxItem(opt, ndx++));
    //imageCombo.GlyphAlignment = DevExpress.Utils.HorzAlignment.Default;
    imageCombo.Items.EndUpdate();
    gv.Columns[colName].ColumnEdit = imageCombo;
  
 * 
 void Automation()
        {
            using (Automation auto = new Automation(0))
            {
                if (auto.ShowDialog() == DialogResult.OK)
                {
                    string FileName = auto.FileName;
                    BrandId = auto.BrandId;
                    SezonId = auto.SezonId;

                    GetDetails("xTopluBrands;xTopluNeed", "ImportSO", DataManager.Datatable2Xml(DataManager.XlsToDatatable(FileName)).ToString(), BrandId, SezonId);
                    bsTopluBrands = new BindingSource(ds, "xTopluBrands");
                    bsTopluNeed = new BindingSource(bsTopluBrands, "FK_xTopluNeed_xTopluBrands_BrandId");

                    //dt.Columns["NEW"].ReadOnly = dt.Columns["TotalQtyNeeded"].ReadOnly = false;
                    //dt = Search(auto.dt, "NEW is not null");
                    cbShowOnly.EditValue = "HEPSİ";
                    autoInUse = true;
                    btnYeni.PerformClick();
                }
            }
        }

        void TopluTalep()
        {
            using (Automation auto = new Automation(1))
            {
                if (auto.ShowDialog() == DialogResult.OK)
                {
                    string FileName = auto.FileName;

                    GetDetails("xTopluBrands;xTopluNeed", "TopluTalep", DataManager.Datatable2Xml(DataManager.XlsToDatatable(FileName)).ToString(), st);
                    //ds.xTopluBrands.Columns.Add("DateSubmitted", typeof(DateTime));
                    //tpToplu.Text = "Toplu - " + ds.xTopluBrands.Compute("COUNT(BrandId)", "DateSubmitted is null");

                    bsTopluBrands = new BindingSource(ds, "xTopluBrands");
                    bsTopluNeed = new BindingSource(bsTopluBrands, "FK_xTopluNeed_xTopluBrands_BrandId");
                    InitLookUp(leToplu, bsTopluBrands, "BrandId", "Brand");
                    //bsTopluBrands.MoveFirst();
                    //bsTopluBrands.EndEdit();
                    //InitGridView(gvToplu, bsTopluBrands);
                    //gvToplu.OptionsBehavior.Editable = false;
                    cbShowOnly.Text = "HEPSİ";  //EditValue
                    topluInUse = true;
                }
            }
        }


        private void btnTopOku_Click(object sender, EventArgs e)
        {
            try
            {
                liste = ConfExpert.Utility.Peripheral.Barcode.ReadDevice();
            }
            catch (Exception)
            {
                using (ConfExpert.Depo.TopListesi getlist = new ConfExpert.Depo.TopListesi(string.Empty))
                    if (getlist.ShowDialog() == DialogResult.OK)
                    {
                        toplar += "," + getlist.toplar;
                        string[] raflar = getlist.raflar.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    }
            }
            finally
            {
                GetDetails("xCECikisK", "GetCikis", CikisEmriId, toplar);
                gvCikis.ExpandAllGroups();
                gvCikis.BestFitColumns();
            }

        }
*/


#region IConfigurationExecuter Members
/*
         * 
         * 
        //Daha önce Program.cs de idi!
        //Configuration configuration;
        //try
        //{
        //    if (!File.Exists(@"configs\gate.xml"))
        //    {
        //        MessageBox.Show(@"Yapılandırma Dosyası 'configs\gate.xml' bulunamadı", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        //        return;
        //    }

        //    configuration = new Configuration(@"configs\gate.xml");
        //    configuration.ParseFile();
        //}
        //catch (Exception cE)
        //{
        //    throw new Exception(@"configs\gate.xml işlenirken '" + (cE.InnerException != null ? cE.InnerException.Message : cE.Message) + "' hatası oluştu");
        //}




         * 
        public void Execute()
        {

        }

        #endregion

        #region IGateManager Members

        public void AddGate(Gate gate)
        {
            Dictionary<string, Gate> readerGates;

            if (gate != null)
            {
                lock (gateList)
                {
                    if (!gateList.ContainsKey(gate.Name))
                    {
                        gateList[gate.Name] = gate;
                    }
                }

                foreach (RFIDReader reader in gate.Readers.Values)
                {
                    lock (readerGateMap)
                    {
                        if (readerGateMap.ContainsKey(reader.Name))
                        {
                            readerGates = readerGateMap[reader.Name];
                        }
                        else
                        {
                            readerGates = new Dictionary<string, Gate>();
                            readerGates[gate.Name] = gate;
                            readerGateMap[reader.Name] = readerGates;
                        }
                        reader.ReaderConnectedEvent += new EventHandler<EventArgs>(ReaderConnectedEventHandler);
                        reader.ReaderDisconnectedEvent += new EventHandler<EventArgs>(ReaderDisconnectedEventHandler);
                        reader.ROAccessReportReceivedEvent += new EventHandler<EventArgs>(ReaderROAccessReportReceivedEventHandler);

                        // RFIDImpinj kütüphanesindeki ImpinjSpeedwayInventoryAwareReader ve bu sınıftan
                        // türeyen alt sınıflar Add/Remove InventoryListener methodlarını kullanarak
                        // eğer kendilerine register olmuş dinleyiciler varsa, Inventory'yi
                        // sürekli açık tutar.
                         
                        IInventoryListener iReader;

                        iReader = reader as IInventoryListener;
                        if (iReader != null)
                        {
                            // Otomatik olarak Inventory'nin sürekli açık olması için Register ol
                            iReader.AddInventoryListener(null);
                        }
                    }
                }

            }
        }

        public void RemoveGate(Gate gate)
        {
            if (gate != null)
            {
                lock (gateList)
                {
                    gateList.Remove(gate.Name);
                }
                lock (readerGateMap)
                {
                    foreach (RFIDReader reader in gate.Readers.Values)
                    {
                        if (readerGateMap.ContainsKey(reader.Name))
                        {
                            readerGateMap[reader.Name].Remove(gate.Name);
                        }

                        reader.ReaderConnectedEvent -= new EventHandler<EventArgs>(ReaderConnectedEventHandler);
                        reader.ReaderDisconnectedEvent -= new EventHandler<EventArgs>(ReaderDisconnectedEventHandler);

                        // EPC Callback
                        reader.ROAccessReportReceivedEvent -= new EventHandler<EventArgs>(ReaderROAccessReportReceivedEventHandler);

                        IInventoryListener iReader;

                        iReader = reader as IInventoryListener;
                        if (iReader != null)
                        {
                            // * Eğer bu okuyucuya kayıtlı dinleyici sayısı 0 olursa
                            // * Inventory'i otomatik olarak kapatılır.
                            // * RemoveInventoryListener ile okuyucuya Register olmuş
                            // * dinleyicilerden bir tanesi remove olur. Toplam sayı 0'a ulaşmışsa
                            // * reader antenleri kapatır
                             

                            iReader.RemoveInventoryListener(null);
                        }
                    }
                }
            }
        }

        string status = "";
        public string Status
        {
            get { return status; }
            set
            {
                status = value;
                SetStatus();
            }
        }

        private void SetStatus()
        {
            if (IsDisposed) return;
            if (!InvokeRequired)
            {
                //lblStatus.Text = status;
            }
            else
            {
                Invoke(new ThreadStart(SetStatus));
            }
        }




        string rfidTag = "";
        public string RFIDTag
        {
            get { return rfidTag; }
            set
            {
                rfidTag = value;
                AddRFIDTag();
            }
        }


        List<int> rfids = new List<int>();

        private void AddRFIDTag()
        {
            if (!InvokeRequired)
            {
                int irfid = int.Parse(RFIDTag.Substring(RFIDTag.Length - 10, 10));
                if (!rfids.Contains(irfid))
                {
                    RefreshMonitorGrid(irfid);
                    rfids.Add(irfid);
                }
                //if (!lbRFID.Items.Contains(rfidTag))
                //{
                //    lbRFID.Items.Add(rfidTag);
                //}
            }
            else
            {
                if (IsDisposed) return;
                Invoke(new ThreadStart(AddRFIDTag));
            }
        }



        public void ReaderConnectedEventHandler(object sender, EventArgs e)
        {
            Status = "Bağlantı kuruldu";
            StopConnectProgress();
        }

        private void StopConnectProgress()
        {
            if (!InvokeRequired)
            {

                //pbConnect.Visible = false;
                //tmrConnect.Enabled = false;
                //btnTemizle.Visible = true;
            }
            else
            {
                Invoke(new ThreadStart(StopConnectProgress));
            }
        }

        public void ReaderDisconnectedEventHandler(object sender, EventArgs e)
        {
        }

        public void ReaderROAccessReportReceivedEventHandler(object sender, EventArgs e)
        {
            RFIDReader reader;
            TypedEventArgs<List<RFIDTagReport<byte>>> eArgs;
            Dictionary<string, Gate> gates;

            eArgs = e as TypedEventArgs<List<RFIDTagReport<byte>>>;
            if (eArgs != null)
            {
                gates = null;
                reader = sender as RFIDReader;
                if (reader != null)
                {
                    lock (readerGateMap)
                    {
                        if (readerGateMap.ContainsKey(reader.Name))
                        {
                            gates = readerGateMap[reader.Name];
                        }
                    }
                }
                for (int i = 0; i < eArgs.Data.Count; i++)
                {
                    if (gates != null)
                    {
                        foreach (Gate gate in gates.Values)
                        {
                            string val = string.Format("{0} {1} {2}", gate.Name, reader.Name, eArgs.Data[i].EPC);                            
                            RFIDTag = val;
                        }
                    }
                    else
                    {
                        string val = string.Format("{1} {2}", reader.Name, eArgs.Data[i].EPC);
                        RFIDTag = val;
                    }
                }
            }
        }
        */
        #endregion


#region LLRP
/*
 * 
 * 
using Org.LLRP.LTK.LLRPV1;
using Org.LLRP.LTK.LLRPV1.DataType;
using Org.LLRP.LTK.LLRPV1.Impinj;
 * 
 * 
void btnStop_Click(object sender, EventArgs e)
        {
            Delete_RoSpec();
        }

        void Delete_RoSpec()
        {
            MSG_DELETE_ROSPEC msg = new MSG_DELETE_ROSPEC();
            msg.ROSpecID = 123; //0?
            MSG_ERROR_MESSAGE msg_err;
            MSG_DELETE_ROSPEC_RESPONSE rsp =
            reader.DELETE_ROSPEC(msg, out msg_err, 2000);
            if (rsp != null)
            {
                // Success
                //XtraMessageBox.Show(rsp.ToString());
            }
            else if (msg_err != null)
            {
                // Error
                XtraMessageBox.Show(msg_err.ToString());
            }
            else
            {
                // Timeout
                XtraMessageBox.Show("Timeout Error.");
            }
        }

        void Add_RoSpec()
        {
            MSG_ERROR_MESSAGE msg_err;
            MSG_ADD_ROSPEC msg = new MSG_ADD_ROSPEC();
            // Reader Operation Spec (ROSpec)
            msg.ROSpec = new PARAM_ROSpec();
            // ROSpec must be disabled by default
            msg.ROSpec.CurrentState = ENUM_ROSpecState.Disabled;
            // The ROSpec ID can be set to any number
            // You must use the same ID when enabling this ROSpec
            msg.ROSpec.ROSpecID = 123;
            // ROBoundarySpec
            // Specifies the start and stop triggers for the ROSpec
            msg.ROSpec.ROBoundarySpec = new PARAM_ROBoundarySpec();
            // Immediate start trigger
            // The reader will start reading tags as soon as the ROSpec is enabled
            msg.ROSpec.ROBoundarySpec.ROSpecStartTrigger =
            new PARAM_ROSpecStartTrigger();
            msg.ROSpec.ROBoundarySpec.ROSpecStartTrigger.ROSpecStartTriggerType =
            ENUM_ROSpecStartTriggerType.Immediate;
            // No stop trigger. Keep reading tags until the ROSpec is disabled.
            msg.ROSpec.ROBoundarySpec.ROSpecStopTrigger = new PARAM_ROSpecStopTrigger();
            msg.ROSpec.ROBoundarySpec.ROSpecStopTrigger.ROSpecStopTriggerType =
            ENUM_ROSpecStopTriggerType.Null;
            // Antenna Inventory Spec (AISpec)
            // Specifies which antennas and protocol to use
            msg.ROSpec.SpecParameter = new UNION_SpecParameter();
            PARAM_AISpec aiSpec = new PARAM_AISpec();
            aiSpec.AntennaIDs = new UInt16Array();
            // Enable all antennas
            aiSpec.AntennaIDs.Add(0);
            // No AISpec stop trigger. It stops when the ROSpec stops.
            aiSpec.AISpecStopTrigger = new PARAM_AISpecStopTrigger();
            aiSpec.AISpecStopTrigger.AISpecStopTriggerType =
            ENUM_AISpecStopTriggerType.Null;
            aiSpec.InventoryParameterSpec = new PARAM_InventoryParameterSpec[1];
            aiSpec.InventoryParameterSpec[0] = new PARAM_InventoryParameterSpec();
            aiSpec.InventoryParameterSpec[0].InventoryParameterSpecID = 1234;
            aiSpec.InventoryParameterSpec[0].ProtocolID = ENUM_AirProtocols.EPCGlobalClass1Gen2;
            msg.ROSpec.SpecParameter.Add(aiSpec);
            // Report Spec
            msg.ROSpec.ROReportSpec = new PARAM_ROReportSpec();
            // Send a report for every tag read
            msg.ROSpec.ROReportSpec.ROReportTrigger =
            ENUM_ROReportTriggerType.Upon_N_Tags_Or_End_Of_ROSpec;
            msg.ROSpec.ROReportSpec.N = 1;
            msg.ROSpec.ROReportSpec.TagReportContentSelector =
            new PARAM_TagReportContentSelector();
            MSG_ADD_ROSPEC_RESPONSE rsp = reader.ADD_ROSPEC(msg, out msg_err, 2000);
            if (rsp != null)
            {
                // Success
                //XtraMessageBox.Show(rsp.ToString());
            }
            else if (msg_err != null)
            {
                // Error
                XtraMessageBox.Show(msg_err.ToString());
            }
            else
            {
                // Timeout
                XtraMessageBox.Show("Timeout Error.");
            }
        }

        void Enable_RoSpec()
        {
            MSG_ERROR_MESSAGE msg_err;
            MSG_ENABLE_ROSPEC msg = new MSG_ENABLE_ROSPEC();
            msg.ROSpecID = 123;
            MSG_ENABLE_ROSPEC_RESPONSE rsp =
            reader.ENABLE_ROSPEC(msg, out msg_err, 2000);
            if (rsp != null)
            {
                // Success
                //XtraMessageBox.Show(rsp.ToString());
            }
            else if (msg_err != null)
            {
                // Error
                XtraMessageBox.Show(msg_err.ToString());
            }
            else
            {
                // Timeout
                XtraMessageBox.Show("Timeout Error.");
            }
        }

        void Disable_RoSpec()
        {
            MSG_ERROR_MESSAGE msg_err;
            MSG_DISABLE_ROSPEC msg = new MSG_DISABLE_ROSPEC();
            msg.ROSpecID = 123;
            MSG_DISABLE_ROSPEC_RESPONSE rsp =
            reader.DISABLE_ROSPEC(msg, out msg_err, 2000);
            if (rsp != null)
            {
                // Success
                //XtraMessageBox.Show(rsp.ToString());
            }
            else if (msg_err != null)
            {
                // Error
                XtraMessageBox.Show(msg_err.ToString());
            }
            else
            {
                // Timeout
                XtraMessageBox.Show("Timeout Error.");
            }
        }

        //int count = 0;
        void OnReportEvent(MSG_RO_ACCESS_REPORT msg)
        {
            // Loop through all the tags in the report
            for (int i = 0; i < msg.TagReportData.Length; i++)
            {
                if (msg.TagReportData[i].EPCParameter.Count > 0)
                {
                    //count++;
                    string epc;
                    // Two possible types of EPC: 96-bit and 128-bit
                    //if (msg.TagReportData[i].EPCParameter[0].GetType() == typeof(PARAM_EPC_96))
                    epc = ((PARAM_EPC_96)(msg.TagReportData[i].EPCParameter[0])).EPC.ToHexString();
                    //else
                    //    epc = ((PARAM_EPCData)(msg.TagReportData[i].EPCParameter[0])).EPC.ToHexString();

                    Invoke(new AddTagCallback(AddTag), epc);

                }
            }
        }

        LLRPClient reader;
        void Start(string addr)
        {
            // Create a LLRPClient instance.
            reader = new LLRPClient();

            //Impinj_Installer.Install();
            //You could also change the search mode to Dual Target:
            //searchMode.InventorySearchMode = ENUM_ImpinjInventorySearchType.Dual_Target; 
            //Connect to the reader.
            //Replace "SpeedwayR-10-25-32" with your reader's hostname.
            //The second argument (2000) is a timeout value in milliseconds.
            //If a connection cannot be established within this timeframe,
            //the call will fail.
            ENUM_ConnectionAttemptStatusType status;
            //reader.Open("SpeedwayR-10-25-32", 2000, out status);
            reader.Open(addr, 2000, out status);

            // Check for a connection error
            if (status != ENUM_ConnectionAttemptStatusType.Success)
            {
                // Could not connect to the reader.
                // Print out the error
                XtraMessageBox.Show(status.ToString());
                // Do something here.
                // Your application should not continue.
                return;
            }
            
            //If you successfully connect to the reader, the next step is to
            //create a delegate. The delegate determines which function gets
            //called when a report event occur.
            
            reader.OnRoAccessReportReceived += new delegateRoAccessReport(OnReportEvent);
            // Send the messages
            Delete_RoSpec();
            Add_RoSpec();
            Enable_RoSpec();
            // Keep reading tags until the user presses return
            //Console.ReadLine();
            // Cleanup the reader by deleting the ROSpec

        }
*/

#endregion
/*
// Define a location before move
int x;
int ilkAyrim;

// Storing begin point (by the left click)
void pictureBox_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
x = e.X;
ilkAyrim = e.Y;
} }

// Moving the picture
void pictureBox_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
pictureBox1.Left += (e.X - x);
pictureBox1.Top += (e.Y - ilkAyrim);
} }
 * 
 * 
//GridView view = gridControlProcessForms.FocusedView as GridView;
//view.CloseEditor();
//view.UpdateCurrentRow(); 

//Note: this code should be performed before showing a modal dialog.


Array arr = Enum.GetValues(typeof(PictureSizeMode));
foreach(PictureSizeMode mode in arr)
    icbSizeMode.Properties.Items.Add(new ImageComboBoxItem(mode.ToString(), mode, -1));

private void icbSizeMode_SelectedIndexChanged(object sender, System.EventArgs e) {
    imageEditSample.Properties.SizeMode = (PictureSizeMode)icbSizeMode.EditValue;
} 


void btnDosyadanOku_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string filePath = openFileDialog1.FileName;
        ds.Clear();
        DataTable dt = XlsParsing.Convert(XlsParsing.ProcessMethod.XlsFile, openFileDialog1.FileName, XlsParsing.TemplateTypes.Sayim);
        GetDetails("xSAYTop;xSAYArtikel", "UpdSayimK", 0, XML.SerializeAll(dt));
        //DesenYonu (yönlü / yönsüz / bare)

        gvTop.BestFitColumns();
        gvArtikel.BestFitColumns();

        btnEslestirmeleriGuncelle.PerformClick();
        //Random rnd = new Random();
        //DevExpress.XtraPrinting.XlsxExportOptions o = new DevExpress.XtraPrinting.XlsxExportOptions();
        //o.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Value;
        //string tempFile = Session.TempDirectory + "\\" + rnd.Next(1000, 9999).ToString() + ".xlsx";
        //gvCounting.ExportToXlsx(tempFile, o);
        //ConfExpert.Utility.IO.File.RunFile(tempFile);
    }
}
select CONVERT(int, 0x000000000155091D)
 *
 * 
 * 
 * 
 
        void btnDosyadanOku_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog1.FileName;
                ds.Clear();
                DataTable dt = XlsParsing.Convert(XlsParsing.ProcessMethod.XlsFile, openFileDialog1.FileName, XlsParsing.TemplateTypes.Sayim);
                GetDetails("xSAYTop;xSAYArtikel", "UpdSayimK", 0, XML.SerializeAll(dt));
                //DesenYonu (yönlü / yönsüz / bare)

                gvTop.BestFitColumns();
                gvArtikel.BestFitColumns();

                btnEslestirmeleriGuncelle.PerformClick();
                //Random rnd = new Random();
                //DevExpress.XtraPrinting.XlsxExportOptions o = new DevExpress.XtraPrinting.XlsxExportOptions();
                //o.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Value;
                //string tempFile = Session.TempDirectory + "\\" + rnd.Next(1000, 9999).ToString() + ".xlsx";
                //gvCounting.ExportToXlsx(tempFile, o);
                //ConfExpert.Utility.IO.File.RunFile(tempFile);
            }
        }* 
 * 
 * 
 *         //foreach (string c in Enum.GetNames(typeof(KnownColor))

 * 
 
        //this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);

        //void pictureEdit1_MouseMove(object sender, MouseEventArgs e)
        //{
        //    if (mouseDown)
        //    {
        //        double angle = Math.Atan2(e.Y - initialP.Y, e.X - initialP.X) * 180 / Math.PI;
        //        this.Text = angle.ToString();

        //        Bitmap b = ResizeBitmap((Bitmap)pictureEdit1.Image, Math.Max(5, (int)Distance(initialP, e.Location)), 25);
        //        b.MakeTransparent(Color.White);

        //        //b = RotateImage(b, (float)-angle); 

        //        Graphics g = pictureEdit1.CreateGraphics();

        //        g.Clear(Color.White);

        //        if (angle < -90)
        //            g.DrawImage(b, initialP.X - (b.Width - 25), initialP.Y - (b.Height - 25));
        //        else if (angle < 0 && angle > -90)
        //            g.DrawImage(b, initialP.X, initialP.Y - (b.Height - 25));
        //        else if (angle > 90)
        //            g.DrawImage(b, initialP.X - (b.Width - 25), initialP.Y);
        //        else
        //            g.DrawImage(b, initialP);

        //        g.Dispose();


        //        b.Dispose();
        //        this.Text += " -- " + pictureEdit1.Image.Width.ToString() + ", " + pictureEdit1.Image.Height.ToString();

        //    }
        //}


        //protected override void OnPaint(PaintEventArgs e)
        //{
        //    Graphics g = e.Graphics;
        //    //g.DrawImage(theImage, ClientRectangle);

        //    g.DrawImage(theImage, new RectangleF(x1, y1, theImage.Width * (1.2f), theImage.Height * (1.2f)));
        //    g.SmoothingMode = SmoothingMode.HighQuality;


        //    //GraphicsPath path = new GraphicsPath();
        //    //e.Graphics.FillPath(Brushes.White, path);
        //    //e.Graphics.DrawPath(Pens.Black, path);
        //}



        //private void DoubleBuffering_Paint(object sender, PaintEventArgs e)
        //{
        //    Graphics g;
        //    g = e.Graphics;
        //    g.SmoothingMode = SmoothingMode.HighQuality;
        //    g.FillRectangle(Brushes.Yellow, new Rectangle(new Point(0, 0), this.ClientSize));
        //    //g.DrawImage(image, 50, 50, 50 + imageSize, 50 + imageSize);
        //}


        //public Image byteArrayToImage(byte[] byteArrayIn)
        //{
        //    MemoryStream ms = new MemoryStream(byteArrayIn);
        //    Image returnImage = Image.FromStream(ms);
        //    return returnImage;
        //}

        //private void trackBarControl1_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        //{
        //    this.Height = this.Width = 100 * ((int)e.NewValue + 2);
        //}

        //int x1, y1, x2, y2;
        //private void pictureEdit1_MouseDown(object sender, MouseEventArgs e)
        //{
        //    if (e.Button == MouseButtons.Right)
        //    {
        //        pictureEdit1.Image = theImage;
        //        pictureEdit1.Width = this.Width;
        //        pictureEdit1.Height = this.Height;
        //    }
        //    else if (e.Button == MouseButtons.Left)
        //    {
        //        x1 = e.X;
        //        y1 = e.Y;
        //    }
        //}

        //private void pictureEdit1_MouseUp(object sender, MouseEventArgs e)
        //{

        //    if (e.Button == MouseButtons.Left)
        //    {
        //        x2 = e.X;
        //        y2 = e.Y;

        //        try
        //        {

        //            zoom_Rect = pictureEdit1.RectangleToClient(new Rectangle(x1, y1, Math.Abs(x2 - x1), Math.Abs(y2 - y1)));
        //            bmp_cut = new Bitmap(zoom_Rect.Width, zoom_Rect.Height);

        //            Graphics g = Graphics.FromImage(bmp_cut);
        //            image = pictureEdit1.Image;
        //            g.DrawImage(image, 0, 0, zoom_Rect, GraphicsUnit.Pixel);
        //            pictureEdit1.Image = bmp_cut;
        //            g.Dispose();




        //            //pictureEdit1.SetBounds(x1, y1, Math.Abs(x2 - x1), Math.Abs(y2 - y1));
        //            //pictureEdit1.Image = ResizeBitmap((Bitmap)pictureEdit1.Image, Math.Max(5, Math.Abs(x2 - x1)), Math.Max(5, Math.Abs(y2 - y1)));

        //        }
        //        catch (Exception Ex)
        //        {
        //            dbg(Ex);
        //        }

        //    }
        //}












        //Boolean mouseDown = false;
        //Point initialP;

        //public Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight)
        //{
        //    Bitmap result = new Bitmap(nWidth, nHeight);
        //    using (Graphics g = Graphics.FromImage((Image)result))
        //    {
        //        g.InterpolationMode = InterpolationMode.NearestNeighbor;
        //        g.DrawImage(b, x1, y1, nWidth, nHeight);
        //    }
        //    return result;
        //}










        //Rectangle rubberBand, zoom_Rect; Bitmap bmp, bmp_cut; float m_Scalef = 1.0f; Image image, myImage;


        //private void pictureEdit1_MouseDown(object sender, MouseEventArgs e)
        //{
        //    Point pt = pictureEdit1.PointToScreen(new Point(e.X, e.Y));
        //    rubberBand = new Rectangle(pt.X, pt.Y, 1, 1);
        //    ControlPaint.DrawReversibleFrame(rubberBand, pictureEdit1.BackColor, FrameStyle.Dashed);
        //    this.Invalidate();
        //}

        //private void pictureEdit1_MouseMove(object sender, MouseEventArgs e)
        //{
        //    if (e.Button != MouseButtons.Left)
        //        return;

        //    ControlPaint.DrawReversibleFrame(rubberBand, pictureEdit1.BackColor, FrameStyle.Dashed);

        //    Point pt = pictureEdit1.PointToScreen(new Point(e.X, e.Y));
        //    rubberBand = new Rectangle(rubberBand.X, rubberBand.Y, pt.X - rubberBand.X, pt.Y - rubberBand.Y);

        //    ControlPaint.DrawReversibleFrame(rubberBand, pictureEdit1.BackColor, FrameStyle.Dashed);

        //    pictureEdit1.Invalidate();

        //}

        //private void pictureEdit1_MouseUp(object sender, MouseEventArgs e)
        //{
        //    if (e.Button == MouseButtons.Left)
        //    {
        //        ControlPaint.DrawReversibleFrame(rubberBand, Color.Black, FrameStyle.Thick);
        //    }

        //}


        //private void button2_Click(object sender, EventArgs e)
        //{
        //    zoom_Rect = pictureEdit1.RectangleToClient(rubberBand);
        //    bmp_cut = new Bitmap(zoom_Rect.Width, zoom_Rect.Height);

        //    Graphics g = Graphics.FromImage(bmp_cut);
        //    image = pictureEdit1.Image;
        //    g.DrawImage(image, 0, 0, zoom_Rect, GraphicsUnit.Pixel);
        //    pictureEdit1.Image = bmp_cut;
        //    g.Dispose();


        //}

        //private void button3_Click(object sender, EventArgs e)
        //{

        //    panel1.MyRefresh();
        //    if (comboBox1.SelectedIndex == 0)
        //        m_Scalef = .25f;
        //    if (comboBox1.SelectedIndex == 1)
        //        m_Scalef = .5f;
        //    if (comboBox1.SelectedIndex == 2)
        //        m_Scalef = .75f;
        //    if (comboBox1.SelectedIndex == 3)
        //        m_Scalef = 1.0f;
        //    if (comboBox1.SelectedIndex == 4)
        //        m_Scalef = 2.0f;

        //    m_Scalef = m_Scalef * 2.0f;

        //    int a_Width, b_Height;
        //    a_Width = (int)(rubberBand.Width * m_Scalef);
        //    b_Height = (int)(rubberBand.Height * m_Scalef);
        //    panel1.Size = new Size(a_Width, b_Height);


        //    myImage = pictureEdit1.Image;
        //    Graphics g = panel1.CreateGraphics();


        //    g.DrawImage(myImage, 0, 0, rubberBand.Width * m_Scalef, rubberBand.Height * m_Scalef);


        //    Invalidate();
        //}


 * 
 * 
 * 
            string liste = string.Empty;
            try
            {
                liste = ConfExpert.Utility.Peripheral.Barcode.ReadDevice();
            }
            catch (Exception)
            {
                using (ConfExpert.Depo.TopListesi toplistesi = new ConfExpert.Depo.TopListesi(string.Empty))
                    if (toplistesi.ShowDialog() == DialogResult.OK)
                        liste = toplistesi.barcodes;
            }
            finally
            {




            string liste = String.Empty;

            for (int i = 0; i < gvGPL.RowCount; i++)
            {
                DataRow row = gvGPL.GetDataRow(i);
                liste += row["GelisPartisiId"].ToString() + ",";
            }
 * 
 * 
             ds.xDDProduct.Columns.Add("QtyReserved", typeof(decimal), "SUM(Child(FK_xDDRezerve_xDDProduct_ProductId).QtyReserved)");
            ds.xDDProduct.Columns.Add("QtyAvailable", typeof(decimal), "QtyOnShelf-isNull(QtyReserved, 0)");

* 
 * 
 * 
 * 
 
        void bsPOLines_CurrentItemChanged(object sender, EventArgs e)
        {
            if (bsPOLines.Current != null)
            {
                ConfExpert.Datasets.MyData.PurchaseOrderLinesRow polRow = ((ConfExpert.Datasets.MyData.PurchaseOrderLinesRow)((DataRowView)bsPOLines.Current).Row);
                if ((polRow.IsReqShipDateNull() && polRow.IsRevShipDateNull()) ||
                    (polRow.IsReqShipMethodIdNull() && polRow.IsRevShipMethodIdNull()))
                    polRow.SetETAVarisTarihiNull();
                else
                {
                    DateTime shipDate = (!polRow.IsRevShipDateNull() ? polRow.RevShipDate : polRow.ReqShipDate);
                    int shipMethodId = (!polRow.IsRevShipMethodIdNull() ? polRow.RevShipMethodId : polRow.ReqShipMethodId);
                    DataRow[] ETADays = AppSession.Lookups.ETA.Select("OriginId = " + OriginId.ToString() + " AND ShipMethodId = " + shipMethodId.ToString());
                    if (ETADays.Length > 0)
                        polRow.ETAVarisTarihi = shipDate.AddDays(Convert.ToDouble(ETADays[0]["ETADays"]));
                    else
                        polRow.SetETAVarisTarihiNull();
                }
            }
        }
 * 
 * 
 
        void YuklemeYapistır(object sender, EventArgs e)
        {
            if (yuklemeRow != null)
                foreach (int rowHandle in gvPOLines.GetSelectedRows())
                    if (rowHandle > -1)
                    {
                        int PurchaseOrderLinesId = intParse(gvPOLines.GetRowCellValue(rowHandle, "PurchaseOrderLinesId"));

                        if (ds.Yukleme.Select("PurchaseOrderLinesId = " + PurchaseOrderLinesId.ToString() +
                            (!yuklemeRow.IsShipDateNull() ? " AND ShipDate = '" + yuklemeRow.ShipDate.ToShortDateString() + "'" : string.Empty) +
                            (!yuklemeRow.IsShipMethodIdNull() ? " AND ShipMethodId = " + yuklemeRow.ShipMethodId.ToString() : string.Empty)).Length == 0)
                        {
                            //kontrol et, varsa ekleme!
                            ConfExpert.Datasets.MyData.YuklemeRow yR = ds.Yukleme.NewYuklemeRow();
                            yR.PurchaseOrderLinesId = PurchaseOrderLinesId;
                            if (!yuklemeRow.IsShipDateNull())
                                yR.ShipDate = yuklemeRow.ShipDate;
                            if (!yuklemeRow.IsShipMethodIdNull())
                                yR.ShipMethodId = yuklemeRow.ShipMethodId;
                            if (!yuklemeRow.IsETAVarisTarihiNull())
                                yR.ETAVarisTarihi = yuklemeRow.ETAVarisTarihi;
                            if (!yR.IsNotesNull())
                                yR.Notes = yuklemeRow.Notes;
                            ds.Yukleme.AddYuklemeRow(yR);
                        }
                    }

        }

        int OriginId = 0;
        ConfExpert.Datasets.MyData.YuklemeRow yuklemeRow;
        string yuklemeBilgisi = "";
        void BuArtikelinYuklemeleri(object sender, EventArgs e)
        {
            Yukleme ilkAyrim = new Yukleme(bsYukleme, OriginId);

            ds.PurchaseOrderLines.Columns["SonYuklemeTarihi"].Expression = ds.PurchaseOrderLines.Columns["ToplamYuklenenMt"].Expression = string.Empty;
            ilkAyrim.ShowDialog();
            ds.PurchaseOrderLines.Columns["SonYuklemeTarihi"].Expression = "MAX(Child(FK_Yukleme_PurchaseOrderLines_PurchaseOrderLinesId).ShipDate)";
            ds.PurchaseOrderLines.Columns["ToplamYuklenenMt"].Expression = "SUM(Child(FK_Yukleme_PurchaseOrderLines_PurchaseOrderLinesId).YuklenenMt)";

            if (ilkAyrim.yuklemeRow != null)
            {
                yuklemeRow = ilkAyrim.yuklemeRow;
                GridManager gm = GridManager.GetGridManager(gvPOLines);
                gm.GridMenu.RemoveMenu(yuklemeBilgisi);
                string YuklemeSekli = AppSession.Lookups.ShipMethod.FindByShipMethodId(ilkAyrim.yuklemeRow.ShipMethodId).Name;
                yuklemeBilgisi = ilkAyrim.yuklemeRow.ShipDate.ToShortDateString() + " / " + YuklemeSekli + " bilgisini seçili artikellere yapıştır";
                gm.GridMenu.AddMenu(yuklemeBilgisi, YuklemeYapistır);
            }

        }
* 
 * 
        void InitListBox(ListBoxControl lb, GridView gv)
        {
            cols = new List<string>();
            for (int i = 0; i < gv.VisibleColumns.Count; i++)
                cols.Add(gv.VisibleColumns[i].FieldName);

            ActiveGrid = gv;
            stats = new List<bool>();
            groups = new List<string>();
            lb.SelectionMode = SelectionMode.MultiExtended;
            MyAddItem(lb, "SiparişNo", "SalesOrderId;SiparisNo");
            MyAddItem(lb, "DesenRenkKalite", "DesenNo;Renk;KaliteId");
            MyAddItem(lb, "Üretici", "UreticiId;UreticiKodu;KaliteAciklama;UreticiKonstruksiyon;UreticiKompozisyon");
            MyAddItem(lb, "Müşteri", "MusteriKodu");

            lb.SelectedIndex = -1;
            lb.SelectedValueChanged += new EventHandler(lb_SelectedValueChanged);
            //foreach(string si in lb.SelectedItems)
            //    lb.Items.Remove(si);

            //lb.ItemCheck += new DevExpress.XtraEditors.Controls.ItemCheckEventHandler(lb_ItemCheck);
        }

        void lb_SelectedValueChanged(object sender, EventArgs e)
        {
            ListBoxControl c = (ListBoxControl)sender;
            for (int i = 0; i < c.Items.Count; i++)
                //if ((c.Items[i].CheckState == CheckState.Checked) ^ stats[i])
                MyVisible(i, c.SelectedIndices.Count > 0 ? c.SelectedIndices.Contains(i) : false);
        }
 * 
 
        void OLD_gv_ShowFilterPopupCheckedListBox(object sender, FilterPopupCheckedListBoxEventArgs e)
        {
            GridView gridView1 = ((GridView)sender);

            e.CheckedComboBox.BeginUpdate();
            object[] obj = gridView1.DataController.FilterHelper.GetUniqueColumnValues(e.Column.ColumnHandle, -1, false, true, null);
            if (obj != null)
                for (int i = e.CheckedComboBox.Items.Count - 1; i >= 0; i--)
                    if (Array.IndexOf(obj, ((DevExpress.XtraGrid.Views.Grid.FilterItem)e.CheckedComboBox.Items[i].Value).Value) == -1)
                        e.CheckedComboBox.Items.RemoveAt(i);

            e.CheckedComboBox.EndUpdate();
        }* 
      * 
private void InitSkins()
        {
            foreach (SkinContainer skin in SkinManager.Default.Skins)
            {
                BarCheckItem bci = new BarCheckItem();
                bci.Caption = skin.SkinName;
                bci.GroupIndex = 1;
                bci.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.SetSkin);
                ribbon.Items.Add(bci);
                bsiTemalar.AddItem(bci);
            }
        }

        private void SetSkin(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(e.Item.Caption);
            //defaultLookAndFeel.LookAndFeel.SetSkinStyle(e.Item.Caption);
        }

        public void SetSkin(string SkinName)
        {
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(SkinName);
            //defaultLookAndFeel.LookAndFeel.SetSkinStyle(SkinName);
        }* 
 * 
 public partial class Brands : XForm
    {
        public Brands()
        {
            InitializeComponent();
            TAM.BrandTableAdapter = new Datasets.MyDataTableAdapters.BrandTableAdapter();
        }

        BindingSource bs;
        private void Brands_Load(object sender, EventArgs e)
        {
            bs = new BindingSource(ds, "Brand");
            InitGridView(gvBrand, bs);
            AddBsToList(bs);

            TAM.BrandTableAdapter.Fill(ds.Brand);
            gvBrand.BestFitColumns();
            btnKaydet.Click += new EventHandler(btnKaydet_Click);
        }

        void btnKaydet_Click(object sender, EventArgs e)
        {
            Save();
        }* 
 * 
 * 
            barManager.ForceLinkCreate();
            barManager.ItemClick += new ItemClickEventHandler(Manager2_ItemClick);

            PopupMenu newPopup3 = new PopupMenu(barManager);
            newPopup3.Name = "Actions";
            foreach (string Message in "Ayrılanlar;Karbel depo;Karbel+Müşteri depo;Karbel+Müşteri+Diğer depo".Split(';'))
            {
                BarButtonItem bbi = new BarButtonItem(barManager, Message, 0, BarShortcut.Empty);

                bbi.Name = Message;
                bbi.GroupIndex = 1;
                //bbi.AllowAllUp = true;
                bbi.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
                newPopup3.AddItems(new BarItem[] { bbi });
            }
            ddbFiltre.DropDownControl = newPopup3;

            barManager.Items["Karbel+Müşteri depo"].PerformClick();
            //barManager.Items[GelisPartisiId > 0 ? "Topların tümü" : "Ayrım için uygun olanlar"].PerformClick();

*         //void Manager2_ItemClick(object sender, ItemClickEventArgs e)
        //{
        //    switch (e.Item.Caption)

 * 
 * 
 * decimal Qty = 0.0M, CQty = 0.0M;
            foreach (DataRow dr in dt.Select(string.Empty, "QtyAllocated DESC"))
            {
                Qty = (decimal)dr["QtyAllocated"];
                if (Qty >= Max - CQty)
                    Qty = Max - CQty;

                ds.xCE.FindByRollId((int)dr["RollId"]).QtySelected = Qty;

                CQty += Qty;
 * }
 * 
 using System; using DevTeam;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;

namespace ConfExpert.Forms.Depo
{
    public partial class TopBol : XPopupForm
    {
        int RollId;
        decimal Length;
        public TopBol(int _RollId, decimal _Length)
        {
            InitializeComponent();
            RollId = _RollId;
            Length = _Length;
            this.Text = "TopBol - " + RollId.ToString();
        }

        DataTable tbl;
        BindingSource bs;
        private void TopBol_Load(object sender, EventArgs e)
        {
            tbl = new DataTable();
            tbl.Columns.Add("Parts", typeof(System.Decimal));
            bs = new BindingSource(tbl, string.Empty);
            InitGridView(gridView1, bs);
            gridView1.OptionsView.ShowAutoFilterRow = false;
            gridView1.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            lblUzunluk.Text = String.Format("Uzunluk: {0:#,##0.##} m.", Length);

            btnBol.Click += new EventHandler(btnBol_Click);
            btnIptal.Click += new EventHandler(btnIptal_Click);
            lblSonParca.Text = String.Format("SonParça: {0:#,##0.##} m.", Length);
            tbl.RowChanged += new DataRowChangeEventHandler(tbl_RowChanged);
            tbl.RowDeleted += new DataRowChangeEventHandler(tbl_RowChanged);
            SonParca = Length;
        }

        decimal SonParca;
        void tbl_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (tbl.Rows.Count > 0)
                SonParca = Length - decimal.Parse(tbl.Compute("SUM(parts)", string.Empty).ToString());

            lblSonParca.Text = String.Format("SonParça: {0:#,##0.##} m.", SonParca);
            lblSonParca.Appearance.ForeColor = (SonParca < 0 ? Color.Red : Color.Black);
        }

        void btnIptal_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        //public DataTable Roll = new DataTable();
        void btnBol_Click(object sender, EventArgs e)
        {
            if (SonParca < 0)
                XtraMessageBox.Show("Parçaların toplam uzunluğu, bölünecek topun uzunluğunu geçemez!");
            else
            {
                gridView1.CloseEditor();
                gridView1.UpdateCurrentRow();

                if (XtraMessageBox.Show("Topların bölündükten sonra tekrar birleştirilmesi mümkün olmayacaktır. Bölmek istediğinizden EMİN MİSİNİZ?", "DİKKAT", MessageBoxButtons.YesNo) == DialogResult.No)
                    this.DialogResult = DialogResult.Cancel;
                else
                {
                    ExecQuery("UpdRollSplitMultiple", RollId, WhoAmI, XML.SerializeAll(tbl));
                    //Allocate.cs de xRtoplar ve CikisEmri.cs de xCE bekleniyor.. ne yapabiliriz, düşün!

                    //Roll = ds.Roll;
                    this.DialogResult = DialogResult.OK;
                }
            }
        }

    }
}* 
 * 
         void gridView2_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
                if (e.Column.FieldName == "Photo")
                {
                    System.IO.MemoryStream ms = new System.IO.MemoryStream(gridView2.GetRowCellValue(e.RowHandle, "Photo") as byte[]);
                    Bitmap im = new Bitmap(ms);
                    e.Graphics.DrawImageUnscaled(im, e.Bounds);
                    e.Handled = true;
                    ms.Close();
                }

        }* 
 * 
 *                 private DataView clone = null;

                private void gridView1_ShownEditor(object sender, System.EventArgs e)
                {
                    DevExpress.XtraGrid.Views.Grid.GridView view;
                    view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                    if (view.FocusedColumn.FieldName == "CityCode" && view.ActiveEditor is DevExpress.XtraEditors.LookUpEdit)
                    {
                        Text = view.ActiveEditor.Parent.Name;
                        DevExpress.XtraEditors.LookUpEdit edit;
                        edit = (DevExpress.XtraEditors.LookUpEdit)view.ActiveEditor;

                        DataTable table = edit.Properties.LookUpData.DataSource as DataTable;
                        clone = new DataView(table);
                        DataRow row = view.GetDataRow(view.FocusedRowHandle);
                        clone.RowFilter = "[CountryCode] = " + row["CountryCode"].ToString();
                        edit.Properties.LookUpData.DataSource = clone;
                    }
                }

                private void gridView1_HiddenEditor(object sender, System.EventArgs e)
                {
                    if (clone != null)
                    {
                        clone.Dispose();
                        clone = null;
                    }
                } 
 * 
  
        Private Function AspectedImage(ByVal ImagePath As String, ByVal SizeWanted As Integer) As Image 

Dim myBitmap, WhiteSpace As System.Drawing.Bitmap 
Dim myGraphics As Graphics 
Dim myDestination As Rectangle 
Dim MaxDimension As Integer 
Dim ReductionRatio As Double 

Try 

'create an instance of bitmap based on a file 
myBitmap = New System.Drawing.Bitmap(ImagePath) 



'create a new square blank bitmap the right size 
If myBitmap.Height >= myBitmap.Width Then MaxDimension = myBitmap.Height Else MaxDimension = myBitmap.Width 
ReductionRatio = SizeWanted / MaxDimension 
WhiteSpace = New System.Drawing.Bitmap(SizeWanted, SizeWanted) 

'get the drawing surface of the new blank bitmap 
myGraphics = Graphic
    s.FromImage(WhiteSpace) 

'find out if the photo is landscape or portrait 
Dim WhiteGap As Double 

If myBitmap.Height > myBitmap.Width Then 'portrait 
WhiteGap = ((myBitmap.Width - myBitmap.Height) / 2) * -1 
myDestination = New Rectangle(x:=CInt(WhiteGap * ReductionRatio), ilkAyrim:=0, Width:=Int(myBitmap.Width * ReductionRatio), Height:=Int(myBitmap.Height * ReductionRatio)) 
Else 'landscape 
WhiteGap = ((myBitmap.Width - myBitmap.Height) / 2) 
'create a destination rectangle 
myDestination = New Rectangle(x:=0, ilkAyrim:=CInt(WhiteGap * ReductionRatio), Width:=Int(myBitmap.Width * ReductionRatio), Height:=Int(myBitmap.Height * ReductionRatio)) 
End If 

'draw the image on the white square 
myGraphics.DrawImage(image:=myBitmap, rect:=myDestination) 
AspectedImage = WhiteSpace 

Catch ex As Exception 
myBitmap = New System.Drawing.Bitmap("") 
AspectedImage = New System.Drawing.Bitmap(4, 4) 
ImageBufferExceeded = True 
MsgBox("Image Buffer exceeded, too many images in memory. If the one(s) you want can't be seen, please restart the application and navigate straight to your images") 
Finally 
myBitmap.Dispose() 
myBitmap = Nothing 
WhiteSpace = Nothing 
End Try 

End Function 

 * 
 *  void FillDeviceCombo()
        {
            WIA.DeviceManager manager = new WIA.DeviceManagerClass();
            string deviceName = string.Empty;

            foreach (WIA.DeviceInfo info in manager.DeviceInfos)
                if (info.Type == WIA.WiaDeviceType.ScannerDeviceType)
                {
                    foreach (WIA.Property p in info.Properties)
                        if (p.Name == "Name")
                            cmbScanners.Properties.Items.Add(((WIA.IProperty)p).get_Value().ToString());

                }
        }
        
        void GetDeviceList()
        {
            //public WIA.Device GetSelectedScanner(string ScannerName)        
            WIA.DeviceManager manager = new WIA.DeviceManagerClass();
            string deviceName = "";

            foreach (WIA.DeviceInfo info in manager.DeviceInfos)
            {
                if (info.Type == WIA.WiaDeviceType.ScannerDeviceType)
                {
                    foreach (WIA.Property p in info.Properties)
                    {
                        if (p.Name == "Name")
                        {
                            deviceName = ((WIA.IProperty)p).get_Value().ToString();
                            if (deviceName == ScannerName)
                            {
                                return info.Connect();
                            }
                        }
                    }
                }
            }
            return null;
        }
 * 
 * 
 WIA ile scanner dan otomatik olarak resim tarama işlemi yapmak. 
( bu örneğin çalışması için bir .net projesi acılır ve com referansı olarak microsoft windows image aq v2.0 eklenir. )

setItem(Item1, "6146", 1);    // tarama rengi özelliği  ( 1-4 arası bir değer verebilirsiniz)
setItem(Item1, "6147", 150);  // yatay çözünürlük bilgisi DPI
setItem(Item1, "6148", 150); // dikey çözünürlük bilgisi DPI
setItem(Item1, "6151", 150 * 8.5); // yatay tarama bölgesi 
setItem(Item1, "6152", 150 * 11); // dikey tarama bölgesi 
setItem(Item1, "4104", 24);  // resmin depth özelliği bilgisi. Eğer bunu set etmez isek bazı scannerlarda renkli tarama yapsak bile hep siyah-beyaz gelir.Özellikle Canon larda :), o yüzden set edilmelidir.


Örnek C# kodu : 

    private void ScanAndSaveOnePage () 
    { 
        WIA.CommonDialog Dialog1 = new WIA.CommonDialogClass(); 
        WIA.DeviceManager DeviceManager1 = new WIA.DeviceManagerClass(); 
        System.Object Object1 = null; 
        System.Object Object2 = null; 
        WIA.Device Scanner = null; 
 
        Scanner = Dialog1.ShowSelectDevice(WIA.WiaDeviceType.ScannerDeviceType, false, false); 
 
        WIA.Item Item1 = Scanner.Items[1]; 

        setItem(Item1, "6146", 1); 
        setItem(Item1, "6147", 150); 
        setItem(Item1, "6148", 150); 
        setItem(Item1, "6151", 150 * 8.5); 
        setItem(Item1, "6152", 150 * 11); 
        setItem(Item1, "4104", 24); 

        WIA.ImageFile Image1 = new WIA.ImageFile(); 
        WIA.ImageProcess ImageProcess1 = new WIA.ImageProcess(); 
        Object1 = (Object)"Convert"; 
        ImageProcess1.Filters.Add(ImageProcess1.FilterInfos.get_Item(ref Object1).FilterID, 0); 
 
        Object1 = (Object)"FormatID"; 
        Object2 = (Object)WIA.FormatID.wiaFormatBMP; 
        ImageProcess1.Filters[1].Properties.get_Item(ref Object1).set_Value(ref Object2); 
 
        Object1 = null; 
        Object2 = null; 
 
        Image1 = (WIA.ImageFile)Item1.Transfer(WIA.FormatID.wiaFormatBMP); 
 
        string DestImagePath = @"C:\test.bmp"; 
        File.Delete(DestImagePath); 
        Image1.SaveFile(DestImagePath); 
    } 
 
    private void setItem (IItem item, object property, object value) 
    { 
        WIA.Property aProperty = item.Properties.get_Item(ref property); 
        aProperty.set_Value(ref value); 
    }
            BindingSource bs = new BindingSource(ds, "Exception");
            GetDetails("Exception", "GetException", ExceptionId);
            RepositoryItemPictureEdit ri = new RepositoryItemPictureEdit();
            ri.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;
            pictureEdit1.Properties.Assign(ri);
            pictureEdit1.DataBindings.Add("EditValue", bs, "Screenshot");* 

 * 
 * 
 * 
         void btnAra_Click(object sender, EventArgs e)
        {
            using (Arama arama = new Arama(ActiveFilter, Nulls))
            {
                if (arama.ShowDialog() == DialogResult.OK)
                {
                    Nulls = arama.Nulls;
                    ActiveFilter = arama.ActiveFilter;
                    int ProductId = arama.ProductId;

                    ds.Clear();
                    GetDetails("ProductBase;PFK;Product;ProductPhoto", "GetStok", ProductId);
                    //dataNavigator1.Visible = ds.Product.Rows.Count > 1;

                    //if (ProductId > 0)
                    //{
                    //    bsProductBase.Position = bsProductBase.Find("ProductBaseId", ProductBaseId);
                    //    gvProduct.FocusedRowHandle = gvProduct.LocateByDisplayText(0, gvProduct.Columns["ProductId"], ProductId.ToString());
                    //    gvProduct.MakeRowVisible(gvProduct.FocusedRowHandle, true);
                    //}

                }
            }
        }
* * 
 * 
 * 
        // solution 1 
        private void LookUpEdit1_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            DataRow Row;
            RepositoryItemLookUpEdit Edit;
            Edit = ((LookUpEdit)sender).Properties;

            if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                return;

            Row = LookupTable.NewRow();
            Row["Name"] = e.DisplayValue;
            LookupTable.Rows.Add(Row);

            e.Handled = true;
        }

        // solution 2 
        private void LookUpEdit1_ProcessNewValue(object sender, DevExpress.XtraEditors.Controls.ProcessNewValueEventArgs e)
        {
            DataRow Row;
            RepositoryItemLookUpEdit Edit;
            Edit = ((LookUpEdit)sender).Properties;

            if (e.DisplayValue == null || Edit.NullText.Equals(e.DisplayValue) || string.Empty.Equals(e.DisplayValue))
                return;

            using (Form2 f = new Form2())
            {
                f.ItemID = "(Auto Number)";
                f.ItemName = e.DisplayValue.ToString();
                if (f.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    e.DisplayValue = f.ItemName;
                    Row = LookupTable.NewRow();
                    Row["Name"] = f.ItemName;
                    LookupTable.Rows.Add(Row);
                }
            }

            e.Handled = true;
        }  * 
 * 
 * 
 * 
 
        public void MakeIntellisenseEnabled(ColumnView cv, string col)
        {
            RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();

            ri.PopupFilterMode = DevExpress.XtraEditors.PopupFilterMode.Contains;  //Default, Contains, StartsWith
            ri.PopupFormMinSize = new System.Drawing.Size(500, 500);
            ri.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
            ri.View.OptionsView.ColumnAutoWidth = false;
            ri.View.OptionsView.EnableAppearanceEvenRow = Session.Preferences.EnableAppearanceEvenRow;
            ri.View.OptionsView.ShowAutoFilterRow = true;
            ri.View.OptionsBehavior.Editable = false;
            ri.View.BestFitMaxRowCount = 50;
            ri.View.OptionsFind.HighlightFindResults = true;
            ri.TextEditStyle = TextEditStyles.Standard; // DisableTextEditor;
            ri.NullText = string.Empty;
            ri.ImmediatePopup = true;

            DataTable dt = new DataTable();
            //dt.Columns.Add(new DataColumn("idx", Type.GetType("System.Int32")));
            dt.Columns.Add(new DataColumn("val", Type.GetType("System.Object")));

            //int cnt = 0;
            dt.BeginLoadData();
            object[] vals = GetUniqueValues(cv, col);
            if (vals != null)
                foreach (object obj in vals)
                    dt.LoadDataRow(new object[] { obj }, true);
            dt.EndLoadData();

            ri.DataSource = dt;
            ri.DisplayMember = ri.ValueMember = "val";
            ri.PopulateViewColumns();

            ri.QueryPopUp += new System.ComponentModel.CancelEventHandler(ri_QueryPopUp);

            //ri.SortColumnIndex = 0;
            //ri.NullText = string.Empty;
            //ri.ShowHeader = false;
            //ri.TextEditStyle = TextEditStyles.Standard;
            ri.ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);
            cv.Columns[col].ColumnEdit = ri;
        }

        object[] GetUniqueValues(ColumnView view, string column)
        {
            MethodInfo mi = typeof(ColumnView).GetMethod("GetFilterPopupValues", BindingFlags.Instance | BindingFlags.NonPublic);
            return (object[])mi.Invoke(view, new object[] { view.Columns[column], false, null });         

        }
* 
 public void RefreshData2()
        {
            try
            {
                DbCommand sel = Session.DataManager.GetStoredProcCommand("GetKompKonst");
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
                sqlDataAdapter.SelectCommand = (SqlCommand)sel;

                DataSet dsNew = new DataSet();
                sqlDataAdapter.Fill(dsNew);

                dsi.xKompozisyon.Clear();
                dsi.xKonstruksiyon.Clear();
                dsi.xCustomerSatis.Clear();
                dsi.Tables["xKompozisyon"].Merge(dsNew.Tables[0]);
                dsi.Tables["xKonstruksiyon"].Merge(dsNew.Tables[1]);
                dsi.Tables["xCustomerSatis"].Merge(dsNew.Tables[2]);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }* 

 *         public static List<T> EnumToList<T>()
        {
            Type enumType = typeof(T);
            // Can't use type constraints on value types, so have to do check like this
            if (enumType.BaseType != typeof(Enum))
                throw new ArgumentException("T must be of type System.Enum");
            return new List<T>(Enum.GetValues(enumType) as IEnumerable<T>);
        }* 
 * 
 * 
 * 
         using DevExpress.Utils;

// Add the enumerator's values as dropdown items to the ImageComboBoxEdit control.
imageComboBoxEdit1.Properties.Items.AddEnum(typeof(HorzAlignment));

// A SelectedIndexChanged event handler of the ImageComboBoxEdit control.
private void imageComboBoxEdit1_SelectedIndexChanged(object sender, System.EventArgs e) {
   if(imageComboBoxEdit1.SelectedIndex > 0) {
      // Get the selected item.
      ImageComboBoxItem item = imageComboBoxEdit1.SelectedItem as ImageComboBoxItem;
      // Apply the selected alignment to a text editor.
      textEdit1.Properties.Appearance.TextOptions.HAlignment = (HorzAlignment)item.Value;
   }* 
 * 
             gleKalite.DataBindings.Add("EditValue", bsPFK, "KL");
            gleRaporBoyu.DataBindings.Add("EditValue", bsProductBase, "RaporBoyuId");
            gleUretici.DataBindings.Add("EditValue", bsPFK, "OUI");
            teUDesenNo.DataBindings.Add("EditValue", bsPFK, "ODN");
            teUKalite.DataBindings.Add("EditValue", bsPFK, "OKL");
            gleDesen.DataBindings.Add("EditValue", bsPFK, "DSN");
            gleOrgu.DataBindings.Add("EditValue", bsPFK, "ORG");
            gleFinish.DataBindings.Add("EditValue", bsPFK, "FNS");
            gleDesenYonu.DataBindings.Add("EditValue", bsPFK, "YON");
            gleEnGrubu.DataBindings.Add("EditValue", bsPFK, "ENG");
            gleGrup.DataBindings.Add("EditValue", bsPFK, "GRP");
            gleKompozisyon.DataBindings.Add("EditValue", bsPFK, "KM");
            gleKonstruksiyon.DataBindings.Add("EditValue", bsPFK, "KN");
            teDesenNo.DataBindings.Add("EditValue", bsPFK, "DN");
            teProductBaseId.DataBindings.Add("Text", bsProductBase, "ProductBaseId");
            teReorderPoint.DataBindings.Add("EditValue", bsProductBase, "ReorderPoint");
            teReorderQty.DataBindings.Add("EditValue", bsProductBase, "ReorderQty");
            meNotlar.DataBindings.Add("EditValue", bsProductBase, "Notes");
            chkSilindi.DataBindings.Add("EditValue", bsProductBase, "Deleted");
 * 
            //gleUretici.Properties.Assign(RI(Rp.Vendor));
            //gleRaporBoyu.Properties.Assign(RI(Rp.RaporBoyu));
            //gleKalite.Properties.Assign(RI(Rp.Kalite));
            //gleDesen.Properties.Assign(RI(Rp.Desen));
            //gleOrgu.Properties.Assign(RI(Rp.Orgu));
            //gleFinish.Properties.Assign(RI(Rp.Finish));

* * 

 * 
 * 
 * 
 * OPTIONS DIALOG
 * private void A_Load(object sender, EventArgs e)
        {
            //kaynaklar:
            //http://msdn.microsoft.com/en-us/library/bdxxw552.aspx  serialize
            //http://msdn.microsoft.com/en-us/library/tz8csy73.aspx  deserialize
            //http://msdn.microsoft.com/en-us/library/bb738528.aspx

            GetDetails("User", "GetUserInfo", "orhan.aykut");   //diğer tabloları ignore ettim!

            A2 oi = new A2();
            try
            {
                if (!ds.User[0].IsSettingsNull())
                    oi = DeserializeObject(ds.User[0].Settings);
            }
            catch
            {
            }

            //initialize a new object with default values
            A2 i = new A2();
            i.ItemName = oi.ItemName != null ? oi.ItemName : "Widget";
            i.Description = oi.Description != null ? oi.Description : "Regular Widget";
            i.Quantity = oi.Quantity > 0 ? oi.Quantity : 10;
            i.UnitPrice = i.UnitPrice > 0 ? oi.UnitPrice : (decimal)2.30;






            int UserId = 17;
            ExecQuery("UpdUserSettings", UserId, SerializeObject(i));      //settings e girilip KAYDET e basılırsa bunu yap!
        }


        private string SerializeObject(A2 o)
        {
            //2 alternatif
            //BinaryFormatter serializer = new BinaryFormatter();
            XmlSerializer serializer = new XmlSerializer(typeof(A2));


            // Create a FileStream to write with.
            MemoryStream ms = new MemoryStream();
            // Serialize the object, and close the TextWriter
            serializer.Serialize(ms, o);

            ms.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, (int)ms.Length);
            return System.Text.Encoding.GetEncoding("ISO-8859-9").GetString(bytes);
        }


        private A2 DeserializeObject(string Message)
        {
            byte[] a = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(Message);

            // A FileStream is needed to read the XML document.
            MemoryStream fs = new MemoryStream(a);

            //2 alternatif
            //BinaryFormatter serializer = new BinaryFormatter();
            //fs.Seek(0, SeekOrigin.Begin);
            //A2 i = (A2)serializer.Deserialize(fs);

            XmlReader reader = XmlReader.Create(fs);
            XmlSerializer serializer = new XmlSerializer(typeof(A2));
            A2 i = (A2)serializer.Deserialize(reader);
            fs.Close();

            return i;
        }

 * 
 *         private void Initialize()
        {
            foreach (MyData.LookUpRow dt in dsi.LookUp.Select("RI = 1"))
            {
                //if (dt.TABLE_NAME != "V_Kumas")
                //{
                RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();
                repositories.Add(dt.LookUpId, ri);

                //if (dt.TABLE_NAME != "V_Kumas")
                    ri.QueryPopUp += new System.ComponentModel.CancelEventHandler(ri_QueryPopUp);
                //else
                //{
                //    ri.View.RowHeight = 32;
                //    ri.QueryPopUp += new System.ComponentModel.CancelEventHandler(risle_QueryPopUp);
                //}


                //}
                //else
                //{
                //    RepositoryItemSearchLookUpEdit ri = new RepositoryItemSearchLookUpEdit();
                //    repositories.Add(dt.LookUpId, ri);
                //    ri.QueryPopUp += new System.ComponentModel.CancelEventHandler(risle_QueryPopUp);
                //    ri.View.RowHeight = 32;
                //}
            }

            luCol.Clear();
            luCol.Merge(Session.DataManager.ExecuteDt("GetLookUps1"));
            //luCol = Session.DataManager.ExecuteDt("GetLookUps1") as MyData.LookUpColumnDataTable;

            foreach (MyData.LookUpRow dt in dsi.LookUp.Select("RI = 1"))
            {
                //DataView dvData = new DataView(dsi.Tables[dt.TABLE_NAME]);
                //if ((dsi.Tables[dt.TABLE_NAME]).Columns.Contains("Deleted"))
                //    dvData.RowFilter = "Deleted=0 OR Deleted is null";

                RepositoryItemGridLookUpEditBase ri = RI(dt.LookUpId) as RepositoryItemGridLookUpEditBase;
                
                //Settings
                //ri.PopupFilterMode = (dt.TABLE_NAME == "V_Kumas" ? DevExpress.XtraEditors.PopupFilterMode.Default : DevExpress.XtraEditors.PopupFilterMode.Contains);  //Default, Contains, StartsWith
                //ri.PopupFilterMode = (dt.TABLE_NAME == "V_Kumas" ? DevExpress.XtraEditors.PopupFilterMode.Default : AppSession.Settings.PopupFilterMode);  //Default, Contains, StartsWith

                ri.PopupFilterMode = AppSession.Settings.PopupFilterMode;
                //search columns via the View's OptionsFind.FindFilterColumns property. In the "StartsWith" or "Contains" mode, the search is performed against a field specified by the RepositoryItemSearchLookUpEdit.DisplayMember property.
                ri.PopupFormMinSize = new System.Drawing.Size(500, 500);
                ri.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                ri.View.OptionsView.ColumnAutoWidth = false;
                ri.View.OptionsView.EnableAppearanceEvenRow = Session.SettingsEnableAppearanceEvenRow;
                ri.View.OptionsView.ShowAutoFilterRow = true;
                ri.View.OptionsBehavior.Editable = false;
                ri.View.BestFitMaxRowCount = 50;
                ri.View.OptionsFind.HighlightFindResults = true;
                ri.TextEditStyle = TextEditStyles.Standard; // DisableTextEditor;
                ri.NullText = string.Empty;
                ri.ImmediatePopup = true;

                //ri.View.OptionsFind.AllowFindPanel = true;
                //ri.View.OptionsView.AllowCellMerge = true;
                //riMaster.AutoComplete = false;            
                //riMaster.ShowDropDown = ShowDropDown.DoubleClick;

                //I have a ComboBoxEdit with AutoComplete=True and TextEditStyle=DisableTextEditor. When the user starts typing and a matching item is found the selection changes to that item, with the series of matching characters hightlighted. Is there a way to get that hightlighted text? 
                //The same suggestion is applied to the ProgressBarControl: it must always use the DisplayFormat and CustomDisplayText regardless of its focused state, because it's a "read-only editor".

                if (dt.TABLE_NAME != "Joker")
                    InitializeRI(ri, dt);
                else
                    InitializeJoker(ri);
            }
            
        }



        
        private void SerializeObject_ORG(string filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem));
            OrderedItem i = new OrderedItem();
            i.ItemName = "Widget";
            i.Description = "Regular Widget";
            i.Quantity = 10;
            i.UnitPrice = (decimal)2.30;
            //i.Calculate();

            // Create a FileStream to write with.
            Stream writer = new FileStream(filename, FileMode.Create);
            // Serialize the object, and close the TextWriter
            serializer.Serialize(writer, i);
            writer.Close();
        }


        private void DeserializeObject_ORG(string filename)
        {
            // Create an instance of the XmlSerializer specifying type and namespace.
            XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem));

            // A FileStream is needed to read the XML document.
            FileStream fs = new FileStream(filename, FileMode.Open);
            XmlReader reader = XmlReader.Create(fs);

            // Declare an object variable of the type to be deserialized.
            OrderedItem i;

            // Use the Deserialize method to restore the object's state.
            i = (OrderedItem)serializer.Deserialize(reader);
            fs.Close();

            // Write out the properties of the object.
            XtraMessageBox.Show(
            i.ItemName + "\t" +
            i.Description + "\t" +
            i.UnitPrice + "\t" +
            i.Quantity);
        }
        


 * 
 * A2.cs (SETTINGS yerine)
* using System; using DevTeam;
namespace ConfExpert.Forms.Depo
{
    [Serializable]
    public class A2
    {
        // This is the class that will be deserialized.
        public string ItemName;
        public string Description;
        public decimal UnitPrice;
        public int Quantity;

    }
}

        private void InitSkins(ComboBoxEdit cmb)
        {
            //if(SkinName.Contains("Office")) groupIndex = 1;
            //else if (DevExpress.DXperience.Demos.LookAndFeelMenu.IsBonusSkin(SkinName)) groupIndex = 2;

            foreach (SkinContainer skin in SkinManager.Default.Skins)
                cmb.Properties.Items.Add(skin.SkinName);
        }
 * 
 * 
 * 
                 //FormType formtype = (FormType)System.Enum.Parse(typeof(FormType), (string)register.GetValue("MRUformtype", "Null"));


                //string SkinName = (string)register.GetValue("SkinName", "DevExpress Style");    //Office 2010 Black

                //bsiTemalar.Visibility = BarItemVisibility.Never;
                //if (SkinName != "Office 2010 Black")
                //{
                //    foreach (BarCheckItemLink bci in bsiTemalar.ItemLinks)
                //        if (bci.Caption == SkinName)
                //        {
                //            bci.Item.PerformClick();
                //            break;
                //        }
                //}


                //bbiTakip.Enabled = (WhoAmI == 17);

* 
 * 
 
        //registry ye yazılanları buraya taşıdıktan sonra oradaki gereksizleri sil!

            //chkMouseDown.CheckedChanged += new EventHandler(chkMouseDown_CheckedChanged);
            //chkFixed.CheckedChanged += new EventHandler(chkFixed_CheckedChanged);
            //colorEdit1.EditValue = Color.FromName(AppSession.MainForm.KstColor1);
            //colorEdit1.EditValueChanged += new EventHandler(colorEdit1_EditValueChanged);
            //chkFixed.Checked = true;

            //RegistryKey register = Registry.CurrentUser.CreateSubKey(@"Software\ConfExpert");
            //AppSession.MainForm.KstColor1 = (string)register.GetValue("KstColor1", "OliveDrab");

        //void colorEdit1_EditValueChanged(object sender, EventArgs e)
        //{
        //    if (colorEdit1.EditValue == null)
        //        colorEdit1.EditValue = Color.Black;

        //    AppSession.MainForm.KstColor1 = ((Color)colorEdit1.EditValue).Name;
        //    bgvKst.RefreshData();
        //}
        //void chkFixed_CheckedChanged(object sender, EventArgs e)
        //{
        //    bgvKst.Bands[0].Fixed = (chkFixed.Checked ? FixedStyle.Left : FixedStyle.None);
        //}

        //void chkMouseDown_CheckedChanged(object sender, EventArgs e)
        //{
        //    bgvKst.OptionsBehavior.EditorShowMode = chkMouseDown.Checked ? DevExpress.Utils.EditorShowMode.MouseDown : DevExpress.Utils.EditorShowMode.Default;   //checkbox hemen seçilebilsin diye!
        //}


        //private void SetSkin(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(e.Item.Caption);
        //    //defaultLookAndFeel.LookAndFeel.SetSkinStyle(e.Item.Caption);
        //}

        //public void SetSkin(string SkinName)
        //{
        //    DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(SkinName);
        //    //defaultLookAndFeel.LookAndFeel.SetSkinStyle(SkinName);
        //}* 
 * 
 * 
         void gvTalepLines_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //yeni satır girilebilsin ama eskisi uneditable olsun diye!  DİKKAT: çok tehlikeli!
            e.Cancel = (gvCikis.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle);
        }*
 * 
 * 
 * 
  Private Sub GridView1_RowCellStyle(ByVal sender As Object, ByVal e As DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs) Handles GridView1.RowCellStyle

        Dim view As GridView = sender

        Select Case e.Column.FieldName

            Case "Field11", "Field12", "Field13"    'etc...

                Dim isEnabled As Boolean = view.GetRowCellValue(e.RowHandle, "Enabled")

                If isEnabled = True Then

                    e.Appearance.BackColor = Color.Transparent

                Else

                    e.Appearance.BackColor = Color.LightGray

                End If

        End Select

    End Sub

* 
 * 
 * 
 
        public DataManager(string connectionString, bool isConnectionStringName)
        {
            if (!isConnectionStringName)
            {
                DbProviderFactory dbProviderFactory = DbProviderFactories.GetFactory("System.Data.SqlClient");
                database = new GenericDatabase(connectionString, dbProviderFactory);
            }
            else
            {
                Random rnd = new Random();
                string RandomCnnStringName = "DynamicConnection_" + rnd.Next(0, 10000);

                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(RandomCnnStringName, connectionString, "System.Data.SqlClient"));
                config.Save();

                ConfigurationManager.RefreshSection("connectionStrings");
                database = DatabaseFactory.CreateDatabase(RandomCnnStringName);
            }

        }

        public DataManager(string server, string db, string id, string password, bool integratedSecurity)
        {
            string connectionString = string.Format("Server={0};Database={1};Integrated Security={2};UID={3};PWD={4}", server, db, integratedSecurity, id, password);
            GenericDatabase gdb = new GenericDatabase(connectionString, System.Data.SqlClient.SqlClientFactory.Instance);
            database = gdb;
        }*
 * 
 * 
 * 
            try
            {
                string MRUform = string.Empty;
                if (this.ActiveMdiChild != null)
                {
                    XForm activeChild = this.ActiveMdiChild as XForm;
                    MRUform = activeChild.ToString().Split(',')[0];
                }
                RegistryKey register = Registry.CurrentUser.CreateSubKey(@"Software\ConfExpert");
                register.SetValue("MRUform", MRUform, RegistryValueKind.String);
                register.SetValue("MRUpage", ribbon.SelectedPage.Text);
                //register.SetValue("SkinName", DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName);
                //if (KstColor1 != null)
                //    register.SetValue("KstColor1", KstColor1);

                Registry.LocalMachine.Flush();
            }
            catch
            {
            }
             
        Ping p = new Ping();
        PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
        void test123()
        {
            try
            {
                Timer t = new Timer() { Interval = 3000 };
                t.Start();
                t.Tick += delegate(object _s, EventArgs _e)
                {
                    PingReply pr = p.Send("10.0.0.4");
                    MyData.UsageHistoryLinesRow uhl = AppSession.Lookups.UsageHistoryLines.NewUsageHistoryLinesRow();
                    uhl.Tarih2 = DateTime.Now;
                    uhl.Ping = (int)pr.RoundtripTime;
                    uhl.AvailableMB = (int)ramCounter.NextValue();
                    AppSession.Lookups.UsageHistoryLines.AddUsageHistoryLinesRow(uhl);
                };

                //PerformanceCounter cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                //float perfCounterValue = cpuCounter.NextValue();

                ////Thread has to sleep for at least 1 sec for accurate value.
                //System.Threading.Thread.Sleep(1000);

                //cpuCounter.NextValue().ToString() + Environment.NewLine + 
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        } * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * //ESKI DATA MANAGER
 * 
 * 
        
    DbCommand sel = dm.GetStoredProcCommand(SP, prm);
    //sel.Connection = dm.ActiveConnection;                
    sel.CommandTimeout = 120;
    sel.CommandType = System.Data.CommandType.StoredProcedure;
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
    sqlDataAdapter.SelectCommand = (SqlCommand)sel;


    if (TableNames == null)
        return dm.ExecScalar(sel);
    else
    {
        ConfExpert.Datasets.MyData ds1 = new ConfExpert.Datasets.MyData();
        ds1.EnforceConstraints = false;

        sqlDataAdapter.TableMappings.Clear();
        string[] Tables = TableNames.Split(new string[] { ";" }, StringSplitOptions.None);
        for (int i = 0; i < Tables.Length; i++)
            sqlDataAdapter.TableMappings.Add("Table" + (i > 0 ? i.ToString() : ""), Tables[i]);
                    
        sqlDataAdapter.Fill((DataSet)ds1);
        ds.Merge(ds1, false, MissingSchemaAction.AddWithKey);

        for (int i = 0; i < Tables.Length; i++)
            ds.Tables[i].AcceptChanges(); //bilahare yeni eklenenler submit edilmesin diye!



        if (WhoAmI == 17)
        {
            System.Collections.IDictionary statistics = (sel.Connection as SqlConnection).RetrieveStatistics();
            Notify(string.Format("BytesReceived: {0:###,#}", statistics["BytesReceived"]));
        }
                    
    }
             


        //DbConnection activeConnection;
        //public DbConnection ActiveConnection
        //{
        //    get
        //    {
        //        if (activeConnection == null)
        //        {
        //            activeConnection = database.CreateConnection();
        //        }
        //        if (activeConnection.State == ConnectionState.Broken || activeConnection.State == ConnectionState.Closed)
        //        {
        //            activeConnection.Open();
        //        }
        //        return activeConnection;
        //    }
        //}

        //public DbTransaction GetTransaction()
        //{
        //    DbConnection connection = database.CreateConnection();
        //    if (connection.State != ConnectionState.Open)
        //    {
        //        connection.Open();
        //    }
        //    return connection.BeginTransaction();
        //}


        //public static DataTable SelectColumns(DataTable SourceTable, string[] columnNames)
        //{
        //    return SourceTable.DefaultView.ToTable(false, columnNames);
        //}


        //public void AddInParameter(DbCommand command, string name, DbType dbType, object value)
        //{
        //    database.AddInParameter(command, name, dbType, value);
        //}

        //public void AddInParameter(DbCommand command, string name, DbType dbType)
        //{
        //    database.AddInParameter(command, name, dbType);
        //}

        //public DbType GetDbType(object value)
        //{
        //    switch (value.GetType().ToString())
        //    {
        //        case "System.String":
        //            return DbType.String;
        //        case "System.Boolean":
        //            return DbType.Boolean;
        //        case "System.Byte":
        //            return DbType.Byte;
        //        case "System.Int16":
        //            return DbType.Int16;
        //        case "System.Int32":
        //            return DbType.Int32;
        //        case "System.Int64":
        //            return DbType.Int64;
        //        case "System.DateTime":
        //            return DbType.DateTime;
        //        case "System.Decimal":
        //            return DbType.Decimal;
        //        case "System.Double":
        //            return DbType.Double;
        //        case "System.Object":
        //            return DbType.Object;
        //        case "System.Guid":
        //            return DbType.Guid;
        //        default:
        //            return DbType.Object;
        //    }

        //}

        //public void AddInParameter(DbCommand command, string name, object value)
        //{

        //    DbType dbType = GetDbType(value);

        //    if (dbType == DbType.DateTime && ((DateTime)value) == DateTime.MinValue)
        //    {
        //        value = null;
        //    }

        //    if (value != null)
        //    {
        //        database.AddInParameter(command, name, dbType, value);
        //    }
        //    else
        //    {
        //        database.AddInParameter(command, name, dbType, DBNull.Value);
        //    }


        //}

        //public string[] GetStringCommandParameterNames(DbCommand command)
        //{
        //    string[] parts = command.CommandText.Split('@');
        //    string[] names = new string[parts.Length - 1];

        //    for (int i = 1; i < parts.Length; i++)
        //    {
        //        names[i - 1] = "@" + parts[i].Replace("(", "").Replace(")", "").Replace(" ", "").Replace(",", "");
        //    }
        //    return names;
        //}

        //public void AddInParameter(DbCommand command, params object[] parameters)
        //{
        //    string[] names = GetStringCommandParameterNames(command);
        //    object value;
        //    DbType type;
        //    string name;

        //    for (int i = 0; i < parameters.Length; i++)
        //    {
        //        value = parameters[i];
        //        type = GetDbType(value);
        //        name = names[i];
        //        database.AddInParameter(command, name, type, value);
        //    }
        //}

        //public void AddOutParameter(DbCommand dbCommand, string name, DbType dbType, int size)
        //{
        //    database.AddOutParameter(dbCommand, name, dbType, size);
        //}


        //public object ExecScalar(DbCommand dbCommand)
        //{
        //    try
        //    {
        //        object obj = database.ExecScalar(dbCommand);
        //        //parameterValues = null;
        //        return obj;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public object ExecScalar(DbCommand dbCommand, DbTransaction transaction)
        //{
        //    try
        //    {
        //        object obj = database.ExecScalar(dbCommand, transaction);
        //        //parameterValues = null;
        //        return obj;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public object ExecScalar(string tSQL)
        //{
        //    try
        //    {
        //        DbCommand dbCommand = GetCommand(tSQL, CommandType.Text);
        //        object obj = ExecScalar(dbCommand);
        //        //parameterValues = null;
        //        return obj;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public object ExecScalar(string tSQL, DbTransaction transaction)
        //{
        //    try
        //    {
        //        DbCommand dbCommand = GetCommand(tSQL, CommandType.Text);
        //        object obj = ExecScalar(dbCommand, transaction);
        //        //parameterValues = null;
        //        return obj;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}


        //private  object[] parameterValues;

        //public System.Data.Common.DbCommand GetCommand(string tSqlOrSPName, CommandType type)
        //{
        //    System.Data.Common.DbCommand cmd;
        //    switch (type)
        //    {
        //        case CommandType.StoredProcedure:
        //            cmd = database.GetStoredProcCommand(tSqlOrSPName);
        //            //cmd.CommandTimeout = int.Parse(ConfigurationManager.AppSettings["SQLCommandTimeOut"].ToString());
        //            break;
        //        case CommandType.Text:
        //            cmd = database.GetSqlStringCommand(tSqlOrSPName);
        //            //cmd.CommandTimeout = int.Parse(ConfigurationManager.AppSettings["SQLCommandTimeOut"].ToString());
        //            break;
        //        default:
        //            cmd = database.GetStoredProcCommand(tSqlOrSPName);
        //            //cmd.CommandTimeout = int.Parse(ConfigurationManager.AppSettings["SQLCommandTimeOut"].ToString());
        //            break;
        //    }

        //    return cmd;
        //}

        //public DbCommand GetStoredProcCommand(string spName)
        //{
        //    DbCommand command = database.GetStoredProcCommand(spName);
        //    //database.DiscoverParameters(command);
        //    command.Connection = ActiveConnection;
        //    return command;
        //}

        //public DbCommand GetStoredProcCommand(string spName, params object[] parameterValues)
        //{
        //    DbCommand command = database.GetStoredProcCommand(spName, parameterValues);
        //    //database.DiscoverParameters(command);
        //    command.Connection = ActiveConnection;
        //    return command;
        //}


        //public DbCommand GetSqlStringCommand(string tSql)
        //{
        //    //DokumanData.cs ve DokumanGiris i düzelt veya yeniden yaz!

        //    //DbCommand command = database.GetSqlStringCommand(tSql);
        //    //return command;
        //}


        //public int ExecuteNonQuery(DbCommand dbCommand)
        //{
        //    try
        //    {
        //        int i = database.ExecuteNonQuery(dbCommand);
        //        //parameterValues = null;
        //        return i;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public int ExecuteNonQuery(string tSQL)
        //{
        //    try
        //    {
        //        DbCommand dbCommand = GetCommand(tSQL, CommandType.Text);
        //        int i = ExecuteNonQuery(dbCommand);
        //        //parameterValues = null;
        //        return i;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public int ExecuteNonQueryWithSp(string spName, params object[] parameterValues)
        //{
        //    try
        //    {
        //        DbCommand dbCommand = database.GetStoredProcCommand(spName, parameterValues);
        //        int i = database.ExecuteNonQuery(dbCommand);
        //        //parameterValues = null;
        //        return i;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public int ExecuteNonQuery(DbCommand dbCommand, DbTransaction transaction)
        //{
        //    try
        //    {
        //        IsolationLevel iso = transaction.IsolationLevel;

        //        int i = database.ExecuteNonQuery(dbCommand, transaction);
        //        //parameterValues = null;
        //        return i;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}



        //public DataRow ExecuteDatarow(DbCommand dbCommand)
        //{
        //    DataRow dr = null;
        //    try
        //    {
        //        DataTable dt;

        //        dt = database.ExecuteDataSet(dbCommand).Tables[0];
        //        if (dt.Rows.Count > 0)
        //        {
        //            dr = dt.Rows[0];
        //        }

        //        return dr;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public DataTable ExecuteDatatable(DbCommand dbCommand)
        //{
        //    try
        //    {
        //        DataTable dt;

        //        dt = database.ExecuteDataSet(dbCommand).Tables[0];

        //        return dt;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public DataTable ExecuteDatatable(string tSQL)
        //{
        //    try
        //    {
        //        DataTable dt;
        //        DbCommand command = GetCommand(tSQL, CommandType.Text);
        //        dt = ExecuteDatatable(command);

        //        return dt;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

        //public DataRow ExecuteDatarow(string tSQL)
        //{
        //    try
        //    {
        //        DbCommand command = GetCommand(tSQL, CommandType.Text);
        //        return ExecuteDatarow(command);
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}


        //public DataSet ExecuteDataset(DbCommand dbCommand)
        //{
        //    try
        //    {
        //        DataSet ds;
        //        dbCommand.CommandTimeout = 300;
        //        ds = database.ExecuteDataSet(dbCommand);


        //        return ds;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw (ex);
        //    }
        //}

 * 
        
        public void ExecuteNonQuery_Transact()
        {
            Database db = DatabaseFactory.CreateDatabase();
            //Two operations, one to add the order //and another to add order details 
            string sqlCommand = "InsertOrder";
            DbCommand orderCommand = db.GetStoredProcCommand(sqlCommand);
            //Add InsertOrder parameters
            sqlCommand = "InsertOrderDetails";
            DbCommand orderDetailsCommand = db.GetStoredProcCommand(sqlCommand);
            //Add InsertOrderDetails parameters
            using (DbConnection connection = db.CreateConnection())
            {
                connection.Open();
                DbTransaction transaction = connection.BeginTransaction();
                try
                {
                    //Execute the InsertOrder
                    db.ExecuteNonQuery(orderCommand, transaction);
                    //Execute the InsertOrderDetails    
                    db.ExecuteNonQuery(orderDetailsCommand, transaction);
                    //Commit the transaction
                    transaction.Commit();
                }
                catch
                {
                    //Roll back the transaction. 
                    transaction.Rollback();
                }
            }
        }
        
 * 
 * OCTANE
 * 
 
        /*
        void Start(params string[] args)
        {
            try
            {
                // Connect to the reader. "SpeedwayR-10-2A-2B"
                try
                {
                    Reader.Connect(args[0]);
                }
                catch (Exception Ex)
                {
                    XtraMessageBox.Show(Ex.Message);
                    return;
                }
                // Assign an event handler for tag reports. This specifies 
                // which function will be called when tag reports arrive. 
                Reader.TagsReported += new EventHandler<TagsReportedEventArgs>(TagsReportedHandler);
                // Assign an event hadler for logging events. 
                //Reader.Logging += new EventHandler<LoggingEventArgs>(LoggingHandler);
                // Clear all reader settings. 
                Reader.ClearSettings();
                // Get the factory settings for the reader. We will 
                // use these are a starting point and then modify 
                // the settings we're interested in. 
                Settings settings = Reader.QueryFactorySettings();
                // Send a report for every tag seen. 
                settings.Report.Mode = ReportMode.Individual;
                
                // Include the antenna number in the tag report. 
                settings.Report.IncludeAntennaPortNumber = true;
                settings.LowDutyCycle.IsEnabled = true;
                settings.LowDutyCycle.EmptyFieldTimeoutInMs = 3000;
                settings.LowDutyCycle.FieldPingIntervalInMs = 200;

                // Apply the new settings. 
                Reader.ApplySettings(settings);
                // Start reading tags. 

                Reader.Start();
            }
            catch (Exception Ex)
            {
                throw Ex;
            }


            
            //Settings.Antennas[1].IsEnabled = true; // use only antenna 1 
            //Settings.Antennas[2].IsEnabled = false; 
            //settings.Antennas[1].MaxRxSensitivty = true; // setting reader for max sensitivity 
            string rep = string.Empty;
            for (double power = 10.0; power <= 30.0; power += 1.0)
            {
                settings.Antennas[1].TxPowerInDbm = power;
                Reader.ApplySettings(settings);
                TagReport tagReport = Reader.QueryTags(3); //query for 3 seconds at each power setting 
                rep += string.Format("At {0} dBm saw {1} tags", power, tagReport.Tags.Count) + Environment.NewLine;
            }

            XtraMessageBox.Show(rep);
            
        }


        public void TagsReportedHandler(object sender, TagsReportedEventArgs args)
        {
            if (!closing)
                Invoke(new AddTagCallback(AddTag), args.TagReport.Tags);
        }



        private void AddTag(List<Tag> tags)
        {
            // Loop through each tag in the report 
            // and print the EPC and antenna number. 
            foreach (Tag tag in tags)
            {
                //XtraMessageBox.Show("Reader saw {0} on ant#{1}", 
                //tag.Epc, tag.AntennaPortNumber); 
                //}
                if (cbDirection.Checked)    //GİRİŞ
                {
                    if (!rfidsG.Contains(tag.Epc))
                    {
                        rfidsG.Add(tag.Epc);
                        dtG.Rows.Add(intParse(tag.Epc));

                        //if (rfids.Contains(tag.Epc))
                        //    rfids.Remove(tag.Epc);
                        if (dt.Rows.Contains(tag.Epc))
                            dt.Rows.Remove(dt.Rows.Find(intParse(tag.Epc)));
                    }
                }
                else
                {
                    if (!rfids.Contains(tag.Epc))
                    {
                        rfids.Add(tag.Epc);
                        dt.Rows.Add(intParse(tag.Epc));

                        //if (rfidsG.Contains(tag.Epc))
                        //    rfidsG.Remove(tag.Epc);
                        if (dtG.Rows.Contains(tag.Epc))
                            dtG.Rows.Remove(dtG.Rows.Find(intParse(tag.Epc)));
                    }
                }
            }
        }





 * 
 * 
 * 
        System.Timers.Timer tmrRefresher = new System.Timers.Timer(500);
        delegate void UpdateData2SourceHandler();
        private void LV_Load(object sender, EventArgs e)
        {
            //listView1.Items[2].BackColor = Color.FromName("Gold");
            int cnt = 1000;
            for (int i = 0; i < 100; i++)
            {
                cnt += rnd.Next(10);
                listView1.Items.Add(cnt.ToString());
            }
            listView1.ShowGroups = true;
            listView1.View = View.SmallIcon;

            tmrRefresher.Elapsed += new System.Timers.ElapsedEventHandler(Raise);
            tmrRefresher.Enabled = true;
            cl = listView1.Items[0].BackColor;

            //listView1.Visible = false;
        }

        Color cl;
        Random rnd = new Random();
        void Raise(object sender, System.Timers.ElapsedEventArgs e)
        {
            tmrRefresher.Enabled = false;
            this.Invoke(new UpdateData2SourceHandler(ChangeColors));
            tmrRefresher.Enabled = true;
        }


        void ChangeColors()
        {
            listView1.SuspendLayout();
            foreach (ListViewItem lvi in listView1.Items)
                if (lvi.BackColor != cl)
                {
                    lvi.BackColor = Color.Transparent;
                    lvi.ForeColor = Color.LightGray;
                }


            for (int i = 0; i < rnd.Next(10, 30); i++)
                listView1.Items[rnd.Next(100)].BackColor = Color.Gold;
            listView1.ResumeLayout();
        }

        private void DisplayKnownColors(PaintEventArgs e)
        {
            this.Size = new Size(650, 550);

            // Get all the values from the KnownColor enumeration.
            System.Array colorsArray = Enum.GetValues(typeof(KnownColor));
            KnownColor[] allColors = new KnownColor[colorsArray.Length];

            Array.Copy(colorsArray, allColors, colorsArray.Length);

            // Loop through printing out the values' names in the colors 
            // they represent.
            float ilkAyrim = 0;
            float x = 10.0F;

            for (int i = 0; i < allColors.Length; i++)
            {

                // If x is a multiple of 30, start a new column.
                if (i > 0 && i % 30 == 0)
                {
                    x += 105.0F;
                    ilkAyrim = 15.0F;
                }
                else
                {
                    // Otherwise, increment ilkAyrim by 15.
                    ilkAyrim += 15.0F;
                }

                // Create a custom brush from the color and use it to draw
                // the brush's name.
                SolidBrush aBrush = new SolidBrush(Color.FromName(allColors[i].ToString()));
                e.Graphics.DrawString(allColors[i].ToString(),
                    this.Font, aBrush, x, ilkAyrim);

                // Dispose of the custom brush.
                aBrush.Dispose();
            }

        }
* 
 * 
 * 
 * 
 * 
 * 
 ENUM_ImpinjDirection direction = ENUM_ImpinjDirection.From_Side1_To_Side2;   //def. çıkış olsun!
            // check for custom tag direction parameter in the RO_ACCESS_REPORT


            if (msg.Custom != null && false)   //FALSE u kaldır!
            {
                for (int i = 0; i < msg.Custom.Length; i++)
                {
                    // try to make a tag direction report out of it
                    if (msg.Custom[i].GetType() == typeof(PARAM_ImpinjTagInformation))
                    {
                        //directionCount++;
                        PARAM_ImpinjTagInformation iti = (PARAM_ImpinjTagInformation)msg.Custom[i];
                        epc = intParse(iti.EPCData.EPC.ToHexString());
                        direction = iti.ImpinjTagDirection.TagDirection;

                        if (mode == Mode.Cikis)
                        {
                            if (direction == ENUM_ImpinjDirection.From_Side1_To_Side2)
                            {
                                if (!rfidsC.Contains(epc))
                                {
                                    rfidsC.Add(epc);
                                    hit = true;
                                }
                            }
                            else
                                if (rfidsC.Contains(epc))
                                {
                                    rfidsC.Remove(epc);
                                    hit = true;
                                }
                        }
                        else if (mode == Mode.Monitor)
                        {
                            rfidsM.Add(epc, direction == ENUM_ImpinjDirection.From_Side1_To_Side2);
                            hit = true;
                        }

                        //string direc = "Direction: ";
                        //direc += iti.EPCData.EPC.ToHexString();
                        //direc += ("  " + iti.ImpinjTagDirection.TagDirection.ToString());
                        //direc += ("  Confidence: " + iti.ImpinjTagDirection.Confidence.ToString());
                        //XtraMessageBox.Show(direc);
                    }
                }
            }
            else * 
 * 
 * 
 *         //private void cmbViewType_EditValueChanged(object sender, EventArgs e)
        //{
        //    switch (cmbViewType.EditValue.ToString())
        //    {
        //        case "GridView":
        //            gcProduct.MainView = gvProduct;
        //            gvProduct.BestFitColumns();
        //            break;
        //        case "CardView":
        //            gcProduct.MainView = cardView1;
        //            break;
        //    }
        //}
                    /*
                case "Ü&retici Kodları":
                    ProductId = intParse(bsProduct, "ProductId");
                    if (ProductId > 0)
                    {
                        UreticiKodlari mk = new UreticiKodlari(1, ProductId);
                        mk.ShowDialog();
                    }
                    else
                        XtraMessageBox.Show("Önce bir renk/varyant seçmelisiniz.", "Hata");
                    break;

                case "Müşteri &Kodları":
                    ProductId = intParse(bsProduct, "ProductId");
                    if (ProductId > 0)
                    {
                        MusteriKodlari mk = new MusteriKodlari(1, ProductId);
                        mk.ShowDialog();
                    }
                    else
                        XtraMessageBox.Show("Önce bir renk/varyant seçmelisiniz.", "Hata");
                    break;
        
 * 
 * 
 * 
         //private void chkDesenNo_CheckedChanged(object sender, EventArgs e)
        //{
        //    StokGiris_AllowDRK = chkDesenNo.Checked;
        //    if (chkDesenNo.Checked)
        //    {
        //        gvGPL.Columns["DesenNo"].VisibleIndex = ndxP + 1;
        //        gvGPL.Columns["Renk"].VisibleIndex = ndxP + 2;
        //        gvGPL.Columns["KaliteId"].VisibleIndex = ndxP + 3;
        //    }
        //    else
        //        gvGPL.Columns["DesenNo"].Visible = gvGPL.Columns["Renk"].Visible = gvGPL.Columns["KaliteId"].Visible = false;
        //}

                if (XtraMessageBox.Show(drs.Length.ToString() + " yeni artikel için stok kartı açılsın mı?", "Confirm", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No)
                return;
            else
            {
                ds.xSGArticles.Clear();
                GetDetails("xSGArticles", "StokKartiAcGP2", XML.SerializeAll(ds.GelisPartisiLines));
                AppSession.MainForm.RaiseUpdate(null, null);  //eklenen kumaşların, lookup ta çıkması için

                foreach (ConfExpert.Datasets.MyData.xSGArticlesRow r in ds.xSGArticles.Rows)
                    ((ConfExpert.Datasets.MyData.GelisPartisiLinesRow)ds.GelisPartisiLines.FindByGelisPartisiLinesId(r.GelisPartisiLinesId)).ProductId = r.ProductId;

 * 
                 //foreach (ConfExpert.Datasets.MyData.xTGArticlesRow r in ds.xTGArticles.Rows)
                //{
                //    ConfExpert.Datasets.MyData.TalepLinesRow tg = ds.TalepLines.FindByTalepLinesId(r.TalepLinesId);
                //    if (tg != null)
                //            tg.ProductId = r.ProductId;
                //}
                
        void gvBrand_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (chkAllBrands.Checked)
                gvBrand.SetRowCellValue(e.RowHandle, "CustomerId", intParse(bs, "CustomerId"));
           
        }
* * 
 * 
 * 
 * 
 *       void gleCustomer_EditValueChanged(object sender, EventArgs e)
        {

            GridLookUpEdit edit = (GridLookUpEdit)sender;
            int dataSourceIndex = edit.Properties.GetIndexByKeyValue(edit.EditValue);
            bs.Position = dataSourceIndex;
            //int rowHandle = gridView1.GetRowHandle(dataSourceIndex);
            //gridView1.FocusedRowHandle = rowHandle;


            //if (intParse(gleCustomer.EditValue) > 0)
            //    bs.Position = bs.IndexOf(gleCustomer.EditValue);    // gleCustomer.Properties.GetIndexByKeyValue(gleCustomer.EditValue); //GetDataSourceRowIndex

                //bs.Position = gleCustomer.EditValue. AppSession.Lookups.V_Customer.FindByCustomerId(intParse(gleCustomer.EditValue));
        }
 
        void gleCustomer_Closed(object sender, ClosedEventArgs e)
        {
            if (intParse(gleCustomer.EditValue) > -1)
            {
                CustomerId = intParse(intParse(gleCustomer.EditValue));
                ds.Customer.BeginLoadData();
                ds.Clear();
                GetDetails("Customer;Brand;Contact;Address;BankAccount", "GetCustomer", CustomerId);
                ds.Customer.EndLoadData();
                gvBrand.BestFitColumns();
            }
        }

        void gleCustomer_ProcessNewValue(object sender, ProcessNewValueEventArgs e)
        {            
            string newEntry = e.DisplayValue.ToString();
            if (newEntry != string.Empty)
            {
                ds.RejectChanges();
                DialogResult dr = XtraMessageBox.Show("'" + newEntry + "' müşteri ismi veritabanında mevcut değil. Eklemek ister misiniz?", "Yeni", MessageBoxButtons.YesNo);
                if (dr == DialogResult.No)
                {
                    e.Handled = false;
                    return;
                }

                bs.AddNew();
                ((DataTable)((GridLookUpEdit)sender).Properties.DataSource).Rows.Add(null, null, newEntry);
                gleCustomer.Tag = newEntry;
                e.Handled = true;
            }
        }

        
        private void OnRepositoryItemGridLookUpEditCloseUp(object sender, CloseUpEventArgs e)
        {
            if (gridView1.ActiveEditor != null)
                ((TextEdit)gridView1.ActiveEditor).SelectAll();
        }

 * 
 * 
 * 
 * 
 * SAVE()de:
 *      using (TransactionScope scope = new TransactionScope())
        using (SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.ConfExpertConnectionString))

 * 
 *      sqlConnection.Open();
        ds.AcceptChanges(); //yan etkisi olur mu, düşün!
        scope.Complete();

 * 
 * 
 * 
 * 
 *         RepositoryItemLookUpEdit riTip
        {
            get
            {
                RepositoryItemLookUpEdit ri = new RepositoryItemLookUpEdit();
                DataTable table = new DataTable();
                table.Columns.Add("KodTipi", typeof(int));
                table.Columns.Add("Açıklama", typeof(string));
                table.Rows.Add(new object[] { 1, "S" });
                table.Rows.Add(new object[] { 2, "M" });
                table.Rows.Add(new object[] { 3, "Ü" });
                ri.DataSource = table;
                ri.ValueMember = "KodTipi";
                ri.DisplayMember = "Açıklama";
                ri.NullText = string.Empty;
                return ri;

                //lookUpEdit1.EditValue = lookUpEdit1.Properties.GetDataSourceValue(lookUpEdit1.Properties.ValueMember, 0);
            }
        }

 * 
 * 
        public static Color getDominantColor(Bitmap bmp)
        {
            //Used for tally
            int r = 0;
            int g = 0;
            int b = 0;

            int total = 0;

            for (int x = 0; x < bmp.Width; x++)
            {
                for (int ilkAyrim = 0; ilkAyrim < bmp.Height; ilkAyrim++)
                {
                    Color clr = bmp.GetPixel(x, ilkAyrim);

                    r += clr.R;
                    g += clr.G;
                    b += clr.B;

                    total++;
                }
            }

            //Calculate average
            r /= total;
            g /= total;
            b /= total;

            return Color.FromArgb(r, g, b);
        }

 * public struct RGBdata
        {
            public int r;
            public int g;
            public int b;
        }

 * 
 *          backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(backgroundWorker1_DoWork);
            //backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        }

        void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            //string path = (string)e.Argument;
            Session.RepositoryManager.RefreshData();
            //this.Invoke(new UpdateDataSourceHandler(Session.RepositoryManager.RefreshData));
        }

 * 
 * 
 * EksikResimleriAl
 * 
        if (dt2.Rows.Count > 0)
            foreach (MyData.ProductRow r in ds.Product)
                if (!imageList1.Images.ContainsKey(r.ProductId.ToString()))
                    if (!r.IsPhotoNull())
                        imageList1.Images.Add(r.ProductId.ToString(), ConvertByteArrayToImage(r.Photo));


        if (dt2.Rows.Count > 0)
            GetDetails("Product", "GetPhotos", XML.Serialize(dt2));

        foreach (MyData.ProductRow r in ds.Product)
            if (!imageList1.Images.ContainsKey(r.ProductId.ToString()))
                if (!r.IsPhotoMikroNull())
                    imageList1.Images.Add(r.ProductId.ToString(), ConvertByteArrayToImage(r.PhotoMikro));

        list.Images.Add(Image.FromFile("ImageEmpty.bmp"));
 * 
 * 
 * 
        if (dt2.Rows.Count > 0)
            GetDetails("Product", "GetPhotos", XML.Serialize(dt2));

        foreach (MyData.ProductRow r in ds.Product)
            if (!imageList1.Images.ContainsKey(r.ProductId.ToString()))
                if (!r.IsPhotoMikroNull())
                    imageList1.Images.Add(r.ProductId.ToString(), ConvertByteArrayToImage(r.PhotoMikro));* 

 * 
 * 
 * 
        
        #region Test
        System.Timers.Timer tmrTest = new System.Timers.Timer(200);

        int GetNextRackNr(int RackNr)
        {
            if (RackNr < 911)
            {
                if (RackNr % 100 < 11)
                    return RackNr + 1;
                else
                    return (RackNr / 100 + 1) * 100 + 1;
            }
            return 911;
        }

        void Test(object sender, System.Timers.ElapsedEventArgs e)
        {
            //if (rnd.Next(100) == 0 ||
            //    RackAdet[RackNr] > MaxAdet ||
            //    RackMetre[RackNr] > MaxMetre)
            //    RackNr = GetNextRackNr(RackNr);

            AddTag(rnd.Next(1000));
            tmrTest.Interval = rnd.Next(50) + 1;
        } 
        #endregion

 * 
 * 
 * 
 * 
        private void GPO1_ON()
        {
            MSG_ERROR_MESSAGE msg_err = new MSG_ERROR_MESSAGE();
            // this routine turns on 3.3v power in LLRP GPO1 
            // LLRP GPO1 = Hardware PIN 14 / GPOUT0 
            MSG_SET_READER_CONFIG msg = new MSG_SET_READER_CONFIG();
            msg.GPOWriteData = new PARAM_GPOWriteData[1];
            msg.GPOWriteData[0] = new PARAM_GPOWriteData();
            msg.GPOWriteData[0].GPOData = true;
            msg.GPOWriteData[0].GPOPortNumber = 1;
            MSG_SET_READER_CONFIG_RESPONSE rsp =
            reader.SET_READER_CONFIG(msg, out msg_err, 12000);
            //if (rsp != null)
            //{
            //    textBox2.Text = rsp.ToString();
            //}
            //else if (msg_err != null)
            //{
            //    textBox2.Text = rsp.ToString();
            //}
            //else
            //    textBox2.Text = "Commmand time out!";
        }

        private void GPO1_OFF()
        {
            MSG_ERROR_MESSAGE msg_err = new MSG_ERROR_MESSAGE();
            // this routine turns off power in LLRP GPO1 
            // LLRP GPO1 = Hardware PIN 14 / GPOUT0 
            MSG_SET_READER_CONFIG msg = new MSG_SET_READER_CONFIG();
            msg.GPOWriteData = new PARAM_GPOWriteData[1];
            msg.GPOWriteData[0] = new PARAM_GPOWriteData();
            msg.GPOWriteData[0].GPOData = false;
            msg.GPOWriteData[0].GPOPortNumber = 1;
            MSG_SET_READER_CONFIG_RESPONSE rsp =
            reader.SET_READER_CONFIG(msg, out msg_err, 12000);
            //if (rsp != null)
            //{
            //    textBox2.Text = rsp.ToString();
            //}
            //else if (msg_err != null)
            //{
            //    textBox2.Text = rsp.ToString();
            //}
            //else
            //    textBox2.Text = "Commmand time out!";
        }
         * 

        //Now, let's take the example one step further. Suppose you want to use all four GPO ports to represent a binary word. 
        void Set_GPO_Word(int word)
        {
            const int NUM_GPO_PORTS = 4;
            int i, bitVal;
            bool[] bits = new bool[NUM_GPO_PORTS];
            // Loop through the last four bits in the
            // word and store their values in an array
            for (i = 0; i < NUM_GPO_PORTS; i++)
            {
                bitVal = word & 1;
                if (bitVal == 1) bits[i] = true;
                else bits[i] = false;
                word = word >> 1;
            }
            MSG_ERROR_MESSAGE msg_err;
            MSG_SET_READER_CONFIG msg = new MSG_SET_READER_CONFIG();
            // Build the message
            msg.GPOWriteData = new PARAM_GPOWriteData[NUM_GPO_PORTS];
            for (i = 0; i < NUM_GPO_PORTS; i++)
            {
                msg.GPOWriteData[i] = new PARAM_GPOWriteData();
                msg.GPOWriteData[i].GPOPortNumber = (ushort)(i + 1);
                msg.GPOWriteData[i].GPOData = bits[i];
            }
            // Send the message
            MSG_SET_READER_CONFIG_RESPONSE rsp =
            reader.SET_READER_CONFIG(msg, out msg_err, 2000);
            if (rsp != null)
            {
                // Success
                Console.WriteLine(rsp.ToString());
            }
            else if (msg_err != null)
            {
                // Error
                Console.WriteLine(msg_err.ToString());
            }
            else
            {
                // Timeout
                Console.WriteLine("Timeout Error.");
            }
        }         * 

 * 
 * 
 *             // Add RF Phase Angle and Peak RSSI fields to the report
            PARAM_ImpinjTagReportContentSelector contentSelector = new PARAM_ImpinjTagReportContentSelector();
            contentSelector.ImpinjEnableRFPhaseAngle = new PARAM_ImpinjEnableRFPhaseAngle();
            contentSelector.ImpinjEnableRFPhaseAngle.RFPhaseAngleMode = ENUM_ImpinjRFPhaseAngleMode.Enabled;
            contentSelector.ImpinjEnablePeakRSSI = new PARAM_ImpinjEnablePeakRSSI();
            contentSelector.ImpinjEnablePeakRSSI.PeakRSSIMode = ENUM_ImpinjPeakRSSIMode.Enabled;
            // These are custom fields, so they get added this way
            msg.ROSpec.ROReportSpec.Custom.Add(contentSelector);
 * 
 * * 
 


                this.DataSource = Session.DataManager.ExecuteDs("GetBarcodes", tip, MyRange).Tables[0];

                //Code128Generator code128Generator1 = new Code128Generator();
                UPCAGenerator upcaGenerator1 = new UPCAGenerator();

                this.xrBarCode1.DataBindings.Add("Text", null, "RollId", ""); //GelisPartisiLinesId
                this.xrBarCode1.Symbology = upcaGenerator1;

                string FormatString = "{0:#,##0.00}"; //mt'.'
                this.lblTopId1.DataBindings.Add("Text", null, "top1", "");
                this.lblTopId2.DataBindings.Add("Text", null, "top2", "{0:000}");
                this.KaliteAdi.DataBindings.Add("Text", null, "Kalite", "");
                this.DesenNo.DataBindings.Add("Text", null, "DesenNo", "");
                this.Renk.DataBindings.Add("Text", null, "Renk", "");
                this.Metre.DataBindings.Add("Text", null, "Qty", FormatString);

                foreach (XRTableRow r in this.xrTable3.Controls)
                    foreach (XRTableCell c in r.Controls)
                        foreach (XRControl ctrl in c.Controls)
                            if (ctrl is XRLabel)
                            {
                                if (ctrl.Name.StartsWith("xr"))
                                    ((XRLabel)ctrl).Font = new System.Drawing.Font("Eras Light ITC", 8F);

                        //if (c.Name.StartsWith("lbl"))
                                else if (ctrl.Name.StartsWith("Metre"))
                                    ((XRLabel)ctrl).Font = new System.Drawing.Font("Century", 15F);
                                else //if (!c.Name.StartsWith("lblTopId"))
                                    ((XRLabel)ctrl).Font = new System.Drawing.Font("Century", 9F);
                            }


                //((XRLabel)ctrl).Font = new System.Drawing.Font("Eras Light ITC", 8F);            
                //this.xrLabel1.CanGrow = this.xrLabel2.CanGrow = this.xrLabel3.CanGrow = this.xrLabel4.CanGrow = this.xrLabel11.CanGrow = this.xrLabel13.CanGrow = this.xrLabel15.CanGrow = this.xrLabel16.CanGrow = false;
                //this.xrLabel1.Font = this.xrLabel2.Font = this.xrLabel3.Font = new System.Drawing.Font("Century", 10F);
                //this.xrLabel4.Font = new System.Drawing.Font("Century", 18F);
                //this.xrLabel16.Font = new System.Drawing.Font("Century", 12F);
                //this.xrControlStyle1.BackColor = System.Drawing.Color.Gainsboro;    

 * 
 * foreach (string tbl in "xKompozisyon;xKonstruksiyon".Split(';'))
            {
                RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();
                
                //Settings
                ri.PopupFilterMode = AppSession.Settings.PopupFilterMode;  //Default, Contains, StartsWith
                
                ri.PopupFormMinSize = new System.Drawing.Size(500, 500);
                ri.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
                ri.View.OptionsView.ColumnAutoWidth = false;
                ri.View.OptionsView.EnableAppearanceEvenRow = Session.SettingsEnableAppearanceEvenRow;
                ri.View.OptionsView.ShowAutoFilterRow = true;
                ri.View.OptionsBehavior.Editable = false;
                ri.View.BestFitMaxRowCount = 50;
                ri.View.OptionsFind.HighlightFindResults = true;
                ri.TextEditStyle = TextEditStyles.Standard; // DisableTextEditor;
                ri.NullText = string.Empty;
                ri.ImmediatePopup = true;

                ri.DataSource = dsi.Tables[tbl]; //dvData;
                ri.DisplayMember = ri.ValueMember = "Name";
                ri.PopulateViewColumns();

                ri.QueryPopUp += new System.ComponentModel.CancelEventHandler(ri_QueryPopUp);

                ri.ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);
                Rp eTbl = (Rp)Enum.Parse(typeof(Rp), tbl);
                repositories.Add((int)eTbl, ri);
            }
 *
 * 
 * 
 *             gvAra.Columns["DColor"].ColumnEdit = new RepositoryItemColorEdit();
            gvAra.Columns["Bri"].DisplayFormat.FormatType = gvAra.Columns["Sat"].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            gvAra.Columns["Bri"].DisplayFormat.FormatString = gvAra.Columns["Sat"].DisplayFormat.FormatString = "#.###";

            gvAra.Columns["R"].Visible = gvAra.Columns["G"].Visible = gvAra.Columns["B"].Visible = gvAra.Columns["Bri"].Visible = gvAra.Columns["Sat"].Visible = gvAra.Columns["Dist"].Visible = false;

 *
 * 
                //xrGelisPartisiId.Visible = (tip == etikettipi.GelisPartisiId);
                //this.xrGelisPartisiId.Symbology = new UPCAGenerator();
                //this.xrGelisPartisiId.Text = range.Replace(",", "");

                ////Code128Generator code128Generator1 = new Code128Generator();
                //UPCAGenerator upcaGenerator1 = new UPCAGenerator();

                //this.xrBarCode1.DataBindings.Add("Text", null, "RollId", ""); //GelisPartisiLinesId
                //this.xrBarCode1.Symbology = upcaGenerator1;

                //string FormatString = "{0:#,##0.00}"; //mt'.'
                //this.lblTopId1.DataBindings.Add("Text", null, "top1", "");                

                //foreach (XRTableRow r in this.xrTable3.Controls)
                //    foreach (XRTableCell c in r.Controls)
                //        foreach (XRControl ctrl in c.Controls)
                //            if (ctrl is XRLabel)
                //            {
                //                if (ctrl.Name.StartsWith("xr"))
                //                    ((XRLabel)ctrl).Font = new System.Drawing.Font("Eras Light ITC", 8F);

                //        //if (c.Name.StartsWith("lbl"))
                //                else if (ctrl.Name.StartsWith("Metre"))
                //                    ((XRLabel)ctrl).Font = new System.Drawing.Font("Century", 15F);
                //                else //if (!c.Name.StartsWith("lblTopId"))
                //                    ((XRLabel)ctrl).Font = new System.Drawing.Font("Century", 9F);
                //            }


 *
 * 
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {            
            FuzzySearch fuzzy = new FuzzySearch(gvArtikel.GetFocusedRowCellDisplayText("MusteriKodu"));

            if (fuzzy.ShowDialog() == DialogResult.OK)
            {
                if (gvArtikel.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                    gvArtikel.SetFocusedRowCellValue("ProductId", fuzzy.ProductId);
            }
        }

        void gridView1_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //e.Cancel = (sender as GridView).FocusedColumn.FieldName != "NOTLAR";

            switch ((sender as GridView).FocusedColumn.FieldName)
            {
                case "TOPLAR":
                case "MevcutMt":
                    e.Cancel = true;
                    break;

                default:
                    e.Cancel = false;
                    break;
            }
        }


        void btnKaydet_Click(object sender, EventArgs e)
        {
            Save();

            AppSession.MainForm.NotifyMain("Kaydedildi.");
        }
 * 
 *
         void NEWgv_ShowFilterPopupCheckedListBox(object sender, FilterPopupCheckedListBoxEventArgs e)
        {
            if (e.Column.FieldName != "CategoryName") return;
            // Locate and disable checked items that contain specific values.
            for (int i = 0; i < e.CheckedComboBox.Items.Count; i++)
            {
                CheckedListBoxItem item = e.CheckedComboBox.Items[i];
                string itemValue = (string)(item.Value as DevExpress.XtraGrid.Views.Grid.FilterItem).Value;
                if (itemValue == "Seafood" || itemValue == "Condiments")
                {
                    e.CheckedComboBox.Items[i].Enabled = false;
                }
            }
        }
 * 
 * 
 * 
 *          checkedListBoxControl1.DataSource = AppSession.Lookups.SiparisDurumu1;
            checkedListBoxControl1.DisplayMember = "Name";
            checkedListBoxControl1.ValueMember = "SiparisDurumu1Id";
            checkedListBoxControl1.ItemCheck += new DevExpress.XtraEditors.Controls.ItemCheckEventHandler(checkedListBoxControl1_ItemCheck);
            bool val = checkedListBoxControl1.GetItemChecked(0);
            checkedListBoxControl1.SetItemChecked(0, true);

 * 
 *         void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            string Message = string.Empty;

            foreach (object item in checkedListBoxControl1.CheckedItems)
            {
                DataRowView row = item as DataRowView;
                Message += (Message != string.Empty ? " OR " : string.Empty) + "Durum1Id = " + row["SiparisDurumu1Id"].ToString();
            }

            prefilter = Message;
            RefreshFilter();
        }
 * 
 * RepositoryItemComboBox riTip
        {
            get
            {
                RepositoryItemComboBox ri = new RepositoryItemComboBox();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;    //OA*
                ri.Items.AddRange(new object[] { "N", "U", " " });
                return ri;
            }
        }

        
        void btnFilter_Click(object sender, EventArgs e)
        {
            using (KFilter kstFilter = new KFilter(Tumu, SadeceKendim, Durum1, StartDate, EndDate))
            {
                if (kstFilter.ShowDialog() == DialogResult.OK)
                {
                    Tumu = kstFilter.Tumu;
                    SadeceKendim = kstFilter.SadeceKendim;
                    StartDate = kstFilter.StartDate;
                    EndDate = kstFilter.EndDate;
                    Durum1 = kstFilter.SiparisDurumu1;

                    gvKstOzet.BeginDataUpdate();
                    ds.Clear();
                    GetDetails("SipNo;SavedLayouts;xKstOzet", "GetKstOzet", 1, Tumu, SadeceKendim, Durum1, StartDate, EndDate, WhoAmI, 1);
                    gvKstOzet.EndDataUpdate();

                    //lblFilter.Text = (SadeceKendim ? "SadeceKendiSiparişlerim, " : "") + "Durum: " + kstFilter.strDurum;
                }
            }
        }
* 
 * 
 
        public void PasteFromClipboardOrj()
        {
            string[] copiedLines = null;
            bool isSingleCellCopied = false;
            string copiedText = "";

            IDataObject iData = Clipboard.GetDataObject();
            bool isTextCopied = iData.GetDataPresent(DataFormats.Text);
            int cFocusedRowHandle = -1;
            bool hasSelection;
            bool isEditing = false;

            int rowDim = -1;
            int colDim = -1;
            GridCell[] selectedCells = null;
            if (isTextCopied)
            {
                copiedText = (string)iData.GetData(DataFormats.Text);

                isEditing = GridView.IsEditing;

                copiedLines = copiedText.Split('\n', StringSplitOptions.RemoveEmptyEntries);

                rowDim = copiedLines.Length;
                colDim = copiedLines[0].Split('\t', StringSplitOptions.None).Length;

                isSingleCellCopied = (colDim == 1 && rowDim == 1);
                selectedCells = GridView.GetSelectedCells();
                hasSelection = selectedCells.Length > 1;
                #region Gerekli miktarda satır ekle
                //GridView.ActiveFilterEnabled = false;

                //OA! copy-paste

                int rowsBelow = GridView.DataRowCount - GridView.GetFocusedDataSourceRowIndex();
                //GridView.ActiveFilterEnabled = true;
                if (rowDim > rowsBelow && !hasSelection && !GridView.IsNewItemRow(GridView.FocusedRowHandle))
                {
                    if (rowsBelow < 0) rowsBelow = 0;
                    int rowsNeedsToBeAdded = rowDim - rowsBelow;
                    cFocusedRowHandle = GridView.FocusedRowHandle;
                    if (cFocusedRowHandle < 0)
                    {
                        if (GridView.DataRowCount > 0)
                            cFocusedRowHandle = GridView.DataRowCount;
                        else
                            cFocusedRowHandle = 0;
                    }
                    if (cFocusedRowHandle < 0)
                        cFocusedRowHandle = GridView.DataRowCount - 1;

                    for (int i = 0; i < rowsNeedsToBeAdded; i++)
                        GridView.AddNewRow();

                    GridView.CloseEditor();
                    GridView.UpdateCurrentRow();

                    GridView.FocusedRowHandle = cFocusedRowHandle; ;
                }
                #endregion

                #region Edit modundaysa yapıştır ve bitir
                if (isEditing)
                {
                    SetFocusedGridValue(copiedText);
                    return;
                }
                #endregion


            }
            else
                return;


            GridMultiSelectMode currentMode = GridView.OptionsSelection.MultiSelectMode;
            GridView.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CellSelect;

            int xpos = GridView.FocusedColumn.VisibleIndex;
            int ypos = GridView.FocusedRowHandle;

            string valueToPaste = "";

            try
            {
                GridView.BeginUpdate();

                #region Tek hücre kopyalandı, bütün seçili hücrelere yapıştır
                if (isSingleCellCopied)
                {
                    #region Tek hücreyi tüm seçililere yapıştır
                    //if (GridView.FocusedColumn.Name.ToLower().Contains("qty"))
                    valueToPaste = copiedText.Replace(" mt.", "");
                    //else
                    //valueToPaste = copiedLine;

                    //OA: SetFocusedGridValue iki kez çağırılıyor diye burayı kapattım. OK mi?
                    //if (!IsReadOnly(GridView.FocusedColumn))
                    //    SetFocusedGridValue(valueToPaste);
                    if (hasSelection)
                    {
                        foreach (GridCell cell in GridView.GetSelectedCells())
                        {
                            GridView.FocusedRowHandle = cell.RowHandle;
                            GridView.FocusedColumn = cell.Column;
                            if (!IsReadOnly(GridView.FocusedColumn))
                                xSetFocusedGridValue(valueToPaste);
                        }
                    }
                    else
                    {
                        SetFocusedGridValue(valueToPaste);
                    }
                    #endregion
                }
                #endregion

                else
                {
                    if (hasSelection)
                    {
                        int rowIndex = -1;
                        int columnIndex = -1;

                        foreach (int rowHandle in GridView.GetSelectedRows())
                        {
                            rowIndex++;
                            columnIndex = -1;
                            foreach (GridColumn column in GridView.GetSelectedCells(rowHandle))
                            {
                                columnIndex++;
                                GridView.FocusedColumn = column;
                                GridView.FocusedRowHandle = rowHandle;
                                string currentValue = copiedLines[rowIndex % rowDim].Split('\t', StringSplitOptions.None)[columnIndex % colDim].Replace(" mt.", "");
                                SetFocusedGridValue(currentValue);
                            }
                        }
                    }
                    else
                    {
                        GridColumn firstColumn = GridView.FocusedColumn;
                        foreach (string copiedLine in copiedLines)
                        {
                            string[] frags = copiedLine.Split('\t', StringSplitOptions.None);
                            int start = GridView.VisibleColumns.IndexOf(GridView.FocusedColumn);

                            foreach (string frag in frags)
                            {
                                valueToPaste = frag.Replace(" mt.", "");

                                if (!IsReadOnly(GridView.FocusedColumn))
                                    SetFocusedGridValue(valueToPaste);

                                if (frags.Length > 1 && GridView.FocusedColumn.VisibleIndex < GridView.VisibleColumns.Count - 1)
                                    GridView.FocusedColumn = GridView.VisibleColumns[++start];
                                else
                                    break;
                            }
                            GridView.MoveNext();
                            GridView.FocusedColumn = firstColumn;
                        }

                    }



                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (ypos >= 0)
                {
                    GridView.FocusedRowHandle = ypos;
                }

                if (xpos >= 0)
                {
                    GridView.FocusedColumn = GridView.VisibleColumns[xpos];
                }

                GridView.ClearSelection();
                if (!hasSelection)
                {
                    GridView.SelectCell(GridView.FocusedRowHandle, GridView.FocusedColumn);
                }
                else
                {
                    foreach (GridCell gc in selectedCells)
                    {
                        GridView.SelectCell(gc);
                    }

                }


                GridView.EndUpdate();
                GridView.OptionsSelection.MultiSelectMode = currentMode;
            }
        }
 * * 
 * 
 

        void bbiBenchTest_ItemClick(object sender, ItemClickEventArgs e)
        {
            //byte[] bits = System.Text.Encoding.UTF8.GetBytes("HELLO");
            for (int i = 0; i < 5; i++)
            {
                //Session.StartWatcher("UCs." + i.ToString());
                BinaryFormatter fmtobj = new BinaryFormatter();
                fmtobj.TypeFormat = fmtobj.TypeFormat | FormatterTypeStyle.XsdString;

                using (FileStream outfile = new FileStream(Session.AppDataPath + "\\dsi.bin", FileMode.Create, FileAccess.Write))
                    fmtobj.Serialize(outfile, AppSession.Lookups);
                //Session.StopWatcher();


                //Session.StartWatcher("x" + i.ToString());
                AppSession.Lookups.Clear();
                //Session.StopWatcher();


                //Session.StartWatcher("UCds." + i.ToString());
                try
                {
                    using (FileStream infile = new FileStream(Session.AppDataPath + "\\dsi.bin", FileMode.Open, FileAccess.Read))
                    {
                        AppSession.Lookups = fmtobj.Deserialize(infile) as MyData;
                    }
                }
                catch
                {
                }
                finally
                {
                    File.Delete(Session.AppDataPath + "\\dsi.bin");
                    //Session.StopWatcher();
                }
            }

            for (int i = 0; i < 5; i++)
            {
                //Session.StartWatcher("Cs." + i.ToString());
                BinaryFormatter fmtobj = new BinaryFormatter();
                fmtobj.TypeFormat = fmtobj.TypeFormat | FormatterTypeStyle.XsdString;

                using (FileStream outfile = new FileStream(Session.AppDataPath + "\\dsi.bin", FileMode.Create, FileAccess.Write))
                using (DeflateStream DefStream = new DeflateStream(outfile, CompressionMode.Compress, false))
                    fmtobj.Serialize(DefStream, AppSession.Lookups);
                //Session.StopWatcher();


                //Session.StartWatcher("x" + i.ToString());
                AppSession.Lookups.Clear();
                //Session.StopWatcher();


                //Session.StartWatcher("Cds." + i.ToString());
                try
                {
                    using (FileStream infile = new FileStream(Session.AppDataPath + "\\dsi.bin", FileMode.Open, FileAccess.Read))
                    {
                        using (DeflateStream DefStream = new DeflateStream(infile, CompressionMode.Decompress, false))
                        {
                            AppSession.Lookups = fmtobj.Deserialize(DefStream) as MyData;
                        }
                    }
                }
                catch
                {
                }
                finally
                {
                    File.Delete(Session.AppDataPath + "\\dsi.bin");
                    //Session.StopWatcher();
                }
            }




            XtraMessageBox.Show(Session.DebugInfo);
        }
* 
 * 
 * 
 * 
        public void DColor_Load(object sender, EventArgs e)
        {
            int cnt = 0;
            byte[] img = new byte[0];
            while (true)
            {
                string ser = XML.Serialize(ds.Product);
                ds.Product.Clear();
                GetDetails("Product", "GetProduct2", ser);

                if (ds.Product.Rows.Count == 0)
                    break;

                for (int i = 0; i < ds.Product.Rows.Count; i++)
                {
                    MyData.ProductRow skR = ds.Product[i];

                    if (!skR.IsPhotoNull())
                    {
                        img = (byte[])skR.Photo;
                        Color clr = GetDominantColor(ConvertByteArrayToImage(skR.Photo) as Bitmap);
                        skR.DColor = clr.ToArgb();
                        skR.R = clr.R;
                        skR.G = clr.G;
                        skR.B = clr.B;
                        skR.Hue = clr.GetHue();
                        skR.Bri = clr.GetBrightness();
                        skR.Sat = clr.GetSaturation();

                        Notify((cnt++).ToString());
                    }
                }
            }

            Notify("Completed");
        }
 * 
 *
             //string rbString = gleRaporBoyu.Text;
            //double rb = RaporBoyu.R0;
            //= (rbString != String.Empty ? (Scanner.RaporBoyu)Enum.Parse(typeof(Scanner.RaporBoyu), rbString) : Scanner.RaporBoyu.R0);
            //switch (rbString)
            //{
            //    case "< 1 cm.": rb = RaporBoyu.R0; break;
            //    case "1 - 1.9 cm.": rb = RaporBoyu.R1; break;
            //    case "2 - 3.9 cm.": rb = RaporBoyu.R2; break;
            //    case "4 - 9.9 cm.": rb = RaporBoyu.R3; break;
            //    case "> 10 cm.": rb = RaporBoyu.R4; break;
            //}

* 
 * 

        void AyrimCoz(object sender, EventArgs e)
        {
            if (gridView2.GetSelectedRows().Length > 0)
                if (XtraMessageBox.Show("Seçili toplardaki ayrımı iptal etmek istediğinizden emin misiniz?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    List<int> rolls = new List<int>();
                    foreach (int handle in gridView2.GetSelectedRows())
                        rolls.Add(intParse(gridView2.GetRowCellValue(handle, "RollId")));

                    GetDetails("xStoklarOzet", "UpdAyrimCoz", string.Join(";", rolls.ToArray()), WhoAmI);
                    pivotGridControl1.RefreshData();
                    gridControl2.DataSource = pivotGridControl1.Cells.GetFocusedCellInfo().CreateDrillDownDataSource();
                }
        } * 
 * 
 * 
             ds.SepetLines.RemoveAll();
            ds.Sepet.RemoveAll();

            int ProductId, RollId;
            foreach(DataRow r in ds.xStoklar.Select("QtySepet>0"))
            {
                ProductId = intParse(r["ProductId"]);
                if (ds.Sepet.Select("ProductId=" + ProductId.ToString()).Length == 0)
                {
                    MyData.SepetRow sr = ds.Sepet.NewSepetRow();
                    sr.ProductId = ProductId;
                    ds.Sepet.AddSepetRow(sr);
                }
            }

            foreach (DataRow r in ds.xStoklarOzet.Select("QtySelected>0"))
            {
                RollId = intParse(r["RollId"]);
                ProductId = intParse(r["ProductId"]);
                int SepetId = intParse(ds.Sepet.Select("ProductId=" + ProductId.ToString())[0]["SepetId"]);
                if (ds.SepetLines.Select("RollId=" + RollId.ToString()).Length == 0)
                {
                    MyData.SepetLinesRow slr = ds.SepetLines.NewSepetLinesRow();
                    slr.SepetId = SepetId;
                    slr.RollId = RollId;
                    slr.BrandId = intParse(r["BrandId"]);
                    slr.SezonId = intParse(r["SezonId"]);
                    slr.OrderRef = r["OrderRef"].ToString();
                    slr.OwnerId = intParse(r["OwnerId"]);
                    slr.Qty = decimalParse(r["Qty"]);
                    ds.SepetLines.AddSepetLinesRow(slr);
                }
            }* 
 * 
 * 
             barManager.ForceLinkCreate();
            barManager.ItemClick += new ItemClickEventHandler(Manager2_ItemClick);

            PopupMenu newPopup3 = new PopupMenu(barManager);
            newPopup3.Name = "Action";
            foreach (string Message in "Ayrım;Çıkış Emri".Split(';'))
            {
                BarButtonItem bbi = new BarButtonItem(barManager, Message, 0, BarShortcut.Empty);

                bbi.Name = Message;
                bbi.GroupIndex = 1;
                //bbi.AllowAllUp = true;
                bbi.ButtonStyle = DevExpress.XtraBars.BarButtonStyle.Check;
                
                newPopup3.AddItems(new BarItem[] { bbi });

            }
            ddb.DropDownControl = newPopup3;
* 
 * 
 * 
 * 
 * 
        private void CikisEmri7C_Load(object sender, EventArgs e)
        {
            treeList1.DragDrop+=new DragEventHandler(treeList1_DragDrop);
            //new DevExpress.XtraTreeList.Design.XViews(treeList1);
            treeList1.OptionsBehavior.DragNodes = true;


            Image myNewImage = Image.FromFile(@"c:\nokta0.gif");

            treeList1.Painter.NodeDragImages.Images.Add(myNewImage);


            //TreeListNode parentNode = treeList1.Nodes[0];

            // insert a new node as the first child within its parent

            TreeListNode newNode = treeList1.AppendNode(new object[] { "New first child" }, parentNode);

            treeList1.SetNodeIndex(newNode, 0);


        }

        private DragDropEffects GetDragDropEffect(TreeList tl, TreeListNode dragNode)
        {
            TreeListNode targetNode;
            Point p = tl.PointToClient(MousePosition);
            targetNode = tl.CalcHitInfo(p).Node;

            if (dragNode != null && targetNode != null
                && dragNode != targetNode
                && dragNode.ParentNode == targetNode.ParentNode)
                return DragDropEffects.Move;
            else
                return DragDropEffects.None;
        }

        private void treeList1_DragOver(object sender, System.Windows.Forms.DragEventArgs e)
        {
            TreeListNode dragNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode;
            e.Effect = GetDragDropEffect(sender as TreeList, dragNode);
        }

        private void treeList1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
        {
            TreeListNode dragNode, targetNode;
            TreeList tl = sender as TreeList;
            Point p = tl.PointToClient(new Point(e.X, e.Y));

            dragNode = e.Data.GetData(typeof(TreeListNode)) as TreeListNode;
            targetNode = tl.CalcHitInfo(p).Node;

            tl.SetNodeIndex(dragNode, tl.GetNodeIndex(targetNode));
            e.Effect = DragDropEffects.None;
        }

        private void treeList1_CalcNodeDragImageIndex(object sender, DevExpress.XtraTreeList.CalcNodeDragImageIndexEventArgs e)
        {
            TreeList tl = sender as TreeList;
            if (GetDragDropEffect(tl, tl.FocusedNode) == DragDropEffects.None)
                e.ImageIndex = -1;  // no icon
            else
                e.ImageIndex = 1;  // the reorder icon (a curved arrow)
        }



        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            //labelControl1.Text = e.Node.GetDisplayText(0);
        }

 * 
        //void Sepet_TableNewRow(object sender, DataTableNewRowEventArgs e)
        //{
        //    e.Row["UserId"] = WhoAmI;
        //}

        //void gridView2_RowStyle(object sender, RowStyleEventArgs e)
        //{        
        //    //if (gridView2.GetRowCellDisplayText(e.RowHandle, "isGarni") != null)
        //    //    if (gridView2.GetRowCellDisplayText(e.RowHandle, "isGarni") == "G")
        //    //        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        //}

 *
 *             switch (svr)
            {
                case "KADIR-PC":
                case "ORHAN-PC":             
                           break;
                default:
                    break;
            }
            svr = "ERP";


            svr = Environment.MachineName;
            
            #if (DEBUG)
            
            #endif   
 *
 * 
 * 
 private void riAksesuar_EditValueChanged(object sender, System.EventArgs e)
        {
            GridView gv = ((GridLookUpEdit)sender).EditValue;
            int ProductId = intParse(gv.GetFocusedRowCellValue("AksesuarId"));
            if (ProductId > 0)
            {

                ConfExpert.Datasets.MyData.AksesuarRow a = AppSession.Lookups.Aksesuar.FindByAksesuarId(ProductId);
                ////RepositoryItemGridLookUpEdit riGridLookUp = RI(Rp.Aksesuar) as RepositoryItemGridLookUpEdit; //view.Columns["AksesuarId"].ColumnEdit as RepositoryItemGridLookUpEdit;
                //object currentKey = view.GetListSourceRowCellValue(e.ListSourceRowIndex, masterGridKeyField);
                //if (currentKey != null)
                //{
                //    int lookUpGridSelectedRowIndex = riGridLookUp.GetIndexByKeyValue(currentKey);
                //    if (lookUpGridSelectedRowIndex > -1)
                //        e.Value = ((riGridLookUp.DataSource as DataTable).Rows[lookUpGridSelectedRowIndex] as DataRow)[e.Column.FieldName];
                //    else
                //        e.Value = "";

                gv.PostEditor();
                gv.SetFocusedRowCellValue(gv.Columns["BrandId"], a.BrandId);
                gv.SetFocusedRowCellValue(gv.Columns["ProductCategoryId"], a.BrandId);
                gv.SetFocusedRowCellValue(gv.Columns["Boy"], a.BrandId);
                gv.SetFocusedRowCellValue(gv.Columns["Renk"], a.BrandId);
                gv.SetFocusedRowCellValue(gv.Columns["Etiket"], a.BrandId);
                gv.SetFocusedRowCellValue(gv.Columns["Aciklama"], a.BrandId);
                gv.ShowEditor();
            }
        }* 
 *
 * 
 * 
*   switch(r[colName].GetType().ToString())
    {
        case "int": r[colName] = (int)drData[colName]; break;
        case "float":
        case "double":
        case "decimal": r[colName] = (decimal)drData[colName]; break;
        case "date": r[colName] = (DateTime)drData[colName]; break;
        case "string": r[colName] = (string)drData[colName]; break;
        default: r[colName] = drData[colName]; break;

    }

 * 
 * 
 *                 //StreamReader sr = File.OpenText(csfile);
           
                //string line;
                //while ((line = sr.ReadLine()) != null)
                //{
                //    if (line.Trim().Length > 0)
                //    //if (line[0].ToString() != "#")
                //    {
                //        svr = line.Substring(0, line.IndexOf(':')).Trim();
                //        cs = line.Substring(line.IndexOf(':') + 1, line.Length - line.IndexOf(':') - 1).Trim().Replace("Initial Catalog=ConfExpert", "Initial Catalog=ConfExpert" + strTest);
                //    }
                //}

 * 
 * 
        public RepositoryItemGridLookUpEdit IntelliSenseLookupEdit(object dataSource, string valueMember)
        {
            RepositoryItemGridLookUpEdit ri = new RepositoryItemGridLookUpEdit();

            ri.PopupFormMinSize = new System.Drawing.Size(500, 500);
            ri.View.OptionsView.ColumnAutoWidth = false;
            ri.View.BestFitMaxRowCount = 50;
            ri.NullText = string.Empty;

            ri.PopupFilterMode = DevExpress.XtraEditors.PopupFilterMode.Contains;
            ri.AllowNullInput = DevExpress.Utils.DefaultBoolean.False;
            ri.View.OptionsView.EnableAppearanceEvenRow = Session.SettingsEnableAppearanceEvenRow;
            ri.View.OptionsView.ShowAutoFilterRow = true;
            ri.View.OptionsBehavior.Editable = false;
            ri.View.OptionsFind.HighlightFindResults = true;
            ri.TextEditStyle = TextEditStyles.Standard;
            ri.ImmediatePopup = true;

            ri.DataSource = dataSource;
            ri.DisplayMember = ri.ValueMember = valueMember;
            ri.PopulateViewColumns();
            ri.ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue);
            ri.QueryPopUp += new System.ComponentModel.CancelEventHandler(ri_QueryPopUp);
            return ri;
        }

        void ri_ProcessNewValue(object sender, ProcessNewValueEventArgs e)
        {
            e.Handled = true;
        }

        void ri_QueryPopUp(object sender, System.ComponentModel.CancelEventArgs e)
        {
            GridLookUpEdit gle = (GridLookUpEdit)sender;
            gle.Properties.View.BestFitColumns();
            gle.QueryPopUp -= new System.ComponentModel.CancelEventHandler(ri_QueryPopUp);
        }


 * 
         void AddProductToTable(int ProductId, byte[] img)
        {
            MyData.ProductRow pr = ds.Product.FindByProductId(ProductId);
            pr.PhotoLarge = img;
            pr.isProcessed = false;

            
            MyData.ProductRow pr = ds.Product.NewProductRow();
            pr.ProductId = ProductId;
            pr.ProductGUID = Guid.NewGuid();
            pr.PhotoLarge = img;
            pr.isProcessed = false;
            ds.Product.AddProductRow(pr);
        }
        * * 
 * 
 *         //public void c_EditValueChanged(object sender, EventArgs e)
        //{
        //    List<string> lst = new List<string>();
        //    CheckedComboBoxEdit c = (CheckedComboBoxEdit)sender;
        //    for (int i = 0; i < c.Properties.Items.Count; i++)
        //        if (c.Properties.Items[i].CheckState == CheckState.Checked)
        //            lst.Add("Tip=" + (i+1).ToString());
        //    bs.Filter = String.Join(" OR ", lst.ToArray());
        //}
 * 
 * 
 * 
 * void Scan(bool toDisk)
        {
            Image i0, i1, i2;
            Scanner scanner = new Scanner();
            scanner.Scan(out i0, out i1, out i2);    //kumaş için sabitlendi

            if (i0 != null)
            {
                if (toDisk)
                    i2.Save(@"C:\scans\" + ProductId.ToString() + ".png", ImageFormat.Png);



                ProductId = intParse(bsProduct);
                if (ds.xPhoto4.FindByProductId(ProductId) == null)
                {
                    MyData.xPhoto4Row xpr = ds.xPhoto4.NewxPhoto4Row();
                    xpr.ProductId = ProductId;
                    ds.xPhoto4.AddxPhoto4Row(xpr);
                }
                ds.xPhoto4.FindByProductId(ProductId).PhotoOriginal = ConvertImageToByteArray(i2, ImageFormat.Png);

                ExecQuery("UpdPhoto4", XML.SerializePic(ds.xPhoto4));
                
                ds.xPhoto4.Clear();
                if ((++SaveCount) % 5 == 0)
                    GC.Collect();


                
             * 
             * 
             * 
             * 
             * 
             * 
                ds.Product.Clear();
                MyData.ProductRow pr = ds.Product.NewProductRow();
                pr.ProductId = ProductId;
                pr.PhotoMikro = ConvertImageToByteArray(i0, ImageFormat.Png);
                if (!toDisk)
                {
                    pr.Photo = ConvertImageToByteArray(i1, ImageFormat.Png);
                    pr.PhotoLarge = ConvertImageToByteArray(i2, ImageFormat.Png);
                }
                pr.ProductGUID = Guid.NewGuid();
                ds.Product.AddProductRow(pr);

                ExecQuery("UpdPhoto", XML.SerializePic(ds.Product));

                if ((++SaveCount) % 5 == 0)
                    GC.Collect();
                 
            }
        
        }
 *
 * 
 * 
             //gridView1.OptionsView.AllowCellMerge = true;
            //gridView1.CellMerge += new CellMergeEventHandler(gridView1_CellMerge);

            //if (WhoAmI == 1 || WhoAmI == 17)
            //{
            //    GridManager gm3 = GridManager.GetManager(gvTop);
            //    gm3.GridMenu.AddMenu("Seçilenleri Sepete Ekle", secilenleriEkle_Click);

            //    gm3.GridMenu.RowMenu.Items[0].Image = Resources.MenuBar_Plus;
            //    //menuItem = new DXMenuItem("PDF", new EventHandler(exportToPDF), Properties.Resources.PDF);
            //    //subMenu.Items.Add(menuItem);

            //    //navButtonNext
            //}

            //btnSepet.Click += new EventHandler(btnSepet_Click);
* 
 * 
 * 
 *         RepositoryItemHyperLinkEdit hlink = new RepositoryItemHyperLinkEdit();
        gvTalep.Columns["TalepId"].ColumnEdit = hlink;
        hlink.SingleClick = true;
        hlink.OpenLink += new DevExpress.XtraEditors.Controls.OpenLinkEventHandler(hlink_OpenLink);

        void hlink_OpenLink(object sender, DevExpress.XtraEditors.Controls.OpenLinkEventArgs e)
        {
            if (e.EditValue.ToString() != string.Empty)
                AppSession.MainForm.ShowMdiChildForm(typeof(Siparisler.YeniTalep), intParse(e.EditValue.ToString()));
        }
 * 
 * 
 * 
 * switch (ds.xBuffer[0].strVal)
                            {
                                case "OwnerId":
                                    foreach (MyData.xBufferRow r in ds.xBuffer)
                                        Message += r.intVal.ToString() + Environment.NewLine;
                                    XtraMessageBox.Show("OWNERIDleri uyumsuz toplar:\n\n" + Message, "İşlem başarısız");
                                    break;

                                case "YetkisizDepodan":
                                    foreach (MyData.xBufferRow r in ds.xBuffer)
                                        Message += r.intVal.ToString() + Environment.NewLine;
                                    XtraMessageBox.Show("Aşağıdaki topları yetkinizin olmadığı bir depodan aldınız:\n\n" + Message, "İşlem başarısız");
                                    break;

                                case "YetkisizDepoya":
                                    XtraMessageBox.Show("Bu transferi, kendi müşterinizin deposu dışındaki başka bir depoya\nancak Kumaş Dept. yapabilir.\n", "İşlem başarısız");
                                    break;
                            }
                            return;
 *
 * 
 * 
 
        public string SchemaChanges
        {
            get
            {
                return dtSchemaChanges.DataSet.GetXml();
            }
        }
 * 
 * 
        public DataSet Merge(DataSet BaseDataSet, string SecondaryDataSetFile)
        {
            DataSet SecondaryDataSet = DeSerialize(SecondaryDataSetFile);
            BaseDataSet = Merge(BaseDataSet, SecondaryDataSet);

            return BaseDataSet;
        }

        public DataSet Merge(DataSet BaseDataSet, DataSet SecondaryDataSet)
        {
            #region Check SecondaryDataSet

            SecondaryDataSet.Relations.Clear();

            List<string> dtsToDelete = new List<string>();

            foreach (DataTable dataTable in SecondaryDataSet.Tables)
            {
                List<string> colsToDelete = new List<string>();


                 if (!BaseDataSet.Tables.Contains(dataTable.TableName))
                {
                    //Tablo File'da var, DB'de yok : File'dan sil
                    dtsToDelete.Add(dataTable.TableName);
                }
                else
                {
                    if (dataTable.PrimaryKey.Length != BaseDataSet.Tables[dataTable.TableName].PrimaryKey.Length)
                    {
                        dtsToDelete.Add(dataTable.TableName);
                        AddSchemaChange(dataTable.TableName);
                    }
                    else
                    {
                        foreach (DataColumn column in dataTable.Columns)
                        {
                            if (!BaseDataSet.Tables[dataTable.TableName].Columns.Contains(column.ColumnName))
                            {
                                //Sütun File'da var, DB'de yok : File'dan sil
                                colsToDelete.Add(column.ColumnName);
                            }
                            else
                            {
                                if (column.DataType != BaseDataSet.Tables[dataTable.TableName].Columns[column.ColumnName].DataType
                                    //||  column.MaxLength != BaseDataSet.Tables[dataTable.TableName].Columns[column.ColumnName].MaxLength
                                    )
                                {
                                    //Tip farklılığı var: File'dan sil , tekrar iste
                                    //Sadece sütun silinebilir, fakat bu sefer sütun yeni eklendiğinden
                                    //Tablonun diğer sütunlarını getirme, sadece bu sütunu getir demek gerekir.
                                    //Bunun yerine, sütunda bir değişiklik varsa, tablo baştan alınıyor.
                                    dtsToDelete.Add(dataTable.TableName);

                                    AddSchemaChange(dataTable.TableName);
                                    break;
                                }
                            }
                        }
                    }
                    try
                    {
                        foreach (string columnName in colsToDelete)
                        {
                            dataTable.Columns.Remove(columnName);
                        }
                    }
                    catch
                    {
                    }
                }
            }

            foreach (string datatableName in dtsToDelete)
            {
                SecondaryDataSet.Tables[datatableName].Constraints.Clear();
                SecondaryDataSet.Tables.Remove(datatableName);
            }

            #endregion

            #region Check BaseDataSet

            foreach (DataTable dataTable in BaseDataSet.Tables)
            {               
                if (!SecondaryDataSet.Tables.Contains(dataTable.TableName))
                {
                    //Tablo DB'de var, File'da yok : İçerik iste
                    AddSchemaChange(dataTable.TableName);
                }
                else
                {
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        if (!SecondaryDataSet.Tables[dataTable.TableName].Columns.Contains(column.ColumnName))
                        {
                            //Sütun DB'de var , File'da yok : İçerik İste
                            AddSchemaChange(dataTable.TableName);
                            SecondaryDataSet.Tables[dataTable.TableName].Constraints.Clear();
                            SecondaryDataSet.Tables.Remove(dataTable.TableName);
                            break;
                        }
                        //else
                        //{
                        //  Bu kontrol CheckSecondary kısmında handle edilmiş oldu.
                        //}
                    }                    
                }
            }
            
            #endregion

            BaseDataSet.Merge(SecondaryDataSet);

            return BaseDataSet;
        }


        public DataSet Merge(DataSet BaseDataSet, string SecondaryDataSetFile, string SPName, string TableToSearchMaxDate, string ColumnNameToSearchMaxDate, string ColumnToGetTableName)
        {
            DateTime OldTime = DateTime.Now;

            DataSet SecondaryDataSet = DeSerialize(SecondaryDataSetFile);

            Session.Sure1 = (DateTime.Now - OldTime).TotalSeconds;

            BaseDataSet = Merge(BaseDataSet, SecondaryDataSet);

            DateTime maxDate = new DateTime(2000, 1, 1);
            if (BaseDataSet.Tables[TableToSearchMaxDate].Rows.Count > 0)
                maxDate = (DateTime)BaseDataSet.Tables[TableToSearchMaxDate].Compute("MAX("+ColumnNameToSearchMaxDate+")", string.Empty);  //ModifiedOn

            DataSet NewDataSet = Session.DataManager.ExecuteDs(SPName, maxDate, Session.CurrentUser.UserId, SchemaChanges);

            if (NewDataSet.Tables.Count > 0)
            {
                NewDataSet.Tables[0].TableName = TableToSearchMaxDate;
                for (int i = 0; i < NewDataSet.Tables[0].Rows.Count; i++)
                    if (TableToSearchMaxDate != NewDataSet.Tables[0].Rows[i][ColumnToGetTableName].ToString())
                        NewDataSet.Tables[i + 1].TableName = (string)NewDataSet.Tables[0].Rows[i][ColumnToGetTableName];
            }

            //BaseDataSet = Merge(BaseDataSet, NewDataSet);
            BaseDataSet.Merge(NewDataSet);

            return BaseDataSet;
        }

        
        //Tek tablolu bir dataset'i serialize/deserialize etme methodu (KST için)
        public DataSet Merge(DataSet BaseDataSet, string SecondaryDataSetFile, string SPName, string TableName)
        {
            DataSet SecondaryDataSet = DeSerialize(SecondaryDataSetFile);
            BaseDataSet = Merge(BaseDataSet, SecondaryDataSet);

            DateTime maxDate = new DateTime(2000, 1, 1);
            if (BaseDataSet.Tables[TableName].Rows.Count > 0)
                maxDate = (DateTime)BaseDataSet.Tables[TableName].Compute("MAX(ModifiedOn)", string.Empty);

            DataSet NewDataSet = Session.DataManager.ExecuteDs(SPName, maxDate);

            NewDataSet.Tables[0].TableName = TableName;

            //BaseDataSet = Merge(BaseDataSet, NewDataSet);
            BaseDataSet.Merge(NewDataSet);

            return BaseDataSet;
        } 
 * 
 * 
 * //// Dosya varsa, dosyayı kullanıp connection string set etme kısmı
 *   string csfile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ConfExpert") + "\\cs.txt";
            chkIsInLocalNetwork.Enabled = !File.Exists(csfile);
            if (File.Exists(csfile))
            {
                string[] allLines = File.ReadAllLines(csfile);
                string lastNotEmptyLine = string.Empty;

                for (int i = allLines.Length - 1; i > -1; i--)
                {
                    if (allLines[i].Trim() != string.Empty)
                    {
                        lastNotEmptyLine = allLines[i].Trim();
                        break;
                    }
                }

                string[] parts = lastNotEmptyLine.Split(':');
                server = parts[0].Trim();
                chkIsInLocalNetwork.Text = server;

                cnnStrBuilder.ConnectionString = parts[1].Trim();
                cnnStrBuilder.InitialCatalog = "ConfExpert" + DatabaseNamePostFix;
            }
            else


 * 
 * 
 * * 
        void gvAttachment_DoubleClick(object sender, EventArgs e)
        {
            if (gvAttachment.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle)
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        string MD5 = ConfExpert.Utility.Crypto.MD5.GetHashFromFile(openFileDialog1.FileName);
                        if (openFileDialog1.OpenFile() != null)
                        {
                            //On Windows Vista, we have a new version of the browser dialog, which is invoked by "System.Windows.Forms.FileDialog.RunDialogVista" in .Net. It does not have the problem. Even if we use the old file open browser dialog (by setting "AutoUpgradeEnabled") on Vista, it still seems to work fine.
                            byte[] bArr;
                            int fLength;
                            FileToByteArray(openFileDialog1.FileName, out bArr, out fLength);
                            ds.Attachment.Rows.Add(new object[] { Guid.NewGuid(), Path.GetFileName(openFileDialog1.FileName), fLength / 1024, null, SalesOrderId, bArr, MD5 });
                            bsAttachment.EndEdit();
                            TAM.UpdateAll(ds);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: Could not read file from disk. Error: " + ex.Message);
                    }
                    finally
                    {
                        gvAttachment.BestFitColumns();
                    }
                }
        }

        void gvAttachment_Click(object sender, EventArgs e)
        {
            if (gvAttachment.FocusedColumn.FieldName == "FileName" && gvAttachment.FocusedRowHandle != DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            {
                Guid ID = (Guid)gvAttachment.GetRowCellValue(gvAttachment.FocusedRowHandle, "AttachmentId");
                string FileName = (string)gvAttachment.GetRowCellValue(gvAttachment.FocusedRowHandle, "FileName");
                ByteArrayToFile(FileName, ds.Attachment.FindByAttachmentId(ID).BLOB);
            }
        }


        public void ByteArrayToFile(string filePath, byte[] content)
        {
            string FullPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\" + filePath;
            using (FileStream fs = new FileStream(FullPath, FileMode.Create, FileAccess.Write))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(content);
                    bw.Flush();
                }
            }

            ProcessStartInfo info = new ProcessStartInfo();
            info.FileName = FullPath;
            info.ErrorDialog = true;
            Process.Start(info);
        }



        public object Deserialize(byte[] b)
        {
            MemoryStream ms = new MemoryStream(b);
            BinaryFormatter bf = new BinaryFormatter();
            ms.Position = 0;
            return bf.Deserialize(ms);
        }

        uint a, b, c;

        void Mix()
        {
            a -= b; a -= c; a ^= (c >> 13);
            b -= c; b -= a; b ^= (a << 8);
            c -= a; c -= b; c ^= (b >> 13);
            a -= b; a -= c; a ^= (c >> 12);
            b -= c; b -= a; b ^= (a << 16);
            c -= a; c -= b; c ^= (b >> 5);
            a -= b; a -= c; a ^= (c >> 3);
            b -= c; b -= a; b ^= (a << 10);
            c -= a; c -= b; c ^= (b >> 15);
        }

        public string Hash(byte[] data)
        {
            int len = data.Length;
            a = b = 0x9e3779b9;
            c = 0;
            int i = 0;
            while (i + 12 <= len)
            {
                a += (uint)data[i++] |
                    ((uint)data[i++] << 8) |
                    ((uint)data[i++] << 16) |
                    ((uint)data[i++] << 24);
                b += (uint)data[i++] |
                    ((uint)data[i++] << 8) |
                    ((uint)data[i++] << 16) |
                    ((uint)data[i++] << 24);
                c += (uint)data[i++] |
                    ((uint)data[i++] << 8) |
                    ((uint)data[i++] << 16) |
                    ((uint)data[i++] << 24);
                Mix();
            }
            c += (uint)len;
            if (i < len)
                a += data[i++];
            if (i < len)
                a += (uint)data[i++] << 8;
            if (i < len)
                a += (uint)data[i++] << 16;
            if (i < len)
                a += (uint)data[i++] << 24;
            if (i < len)
                b += (uint)data[i++];
            if (i < len)
                b += (uint)data[i++] << 8;
            if (i < len)
                b += (uint)data[i++] << 16;
            if (i < len)
                b += (uint)data[i++] << 24;
            if (i < len)
                c += (uint)data[i++] << 8;
            if (i < len)
                c += (uint)data[i++] << 16;
            if (i < len)
                c += (uint)data[i++] << 24;
            Mix();
            return c.ToString();
        } * 
 * 
 *             //forms.TryGetValue(type.GetHashCode().ToString() + (prm.Length > -1 ? "." + Hash(Serialize(prm)).ToString() : string.Empty), out frm);

            //for (int i = 0; i < mdiManager.Pages.Count; i++)
            //    if (mdiManager.Pages[i].MdiChild.GetType() == type)
            //        frm = (XForm)mdiManager.Pages[i].MdiChild;


 *                 // create an instance of Foo
                //Type t = typeof(Foo); // however you get this...
                //object instance = (Foo)Activator.CreateInstance(t, new object[] { 32 });

            // Open a Splash Screen
            //SplashScreenManager.ShowForm(this, typeof(SplashScreen1), true, true, false);
            // The splash screen will be opened in a separate thread. To interact with it, use the SendCommand method.
            //for (int i = 1; i <= 100; i++)
            //{
            //    SplashScreenManager.Default.SendCommand(SplashScreen1.SplashScreenCommand.SetProgress, i);
            //    //To process commands, override the SplashScreen.ProcessCommand method.
            //    Thread.Sleep(25);
            //}
            //this.Hide();

 * 
 * 
        public static int RotateLeft(int value, int count)
        {
            uint val = (uint)value;
            return (int)((val << count) | (val >> (32 - count)));
        }
 * 
 * 
 * 
        public static int Pow2(int count)
        {
            uint val = (uint)1;
            return (int)((val << count) | (val >> (32 - count)));
        }
 * 
 * 
            try
            {
                RegistryKey register = Registry.CurrentUser.CreateSubKey(@"Software\ConfExpert");

                if (AppSession.SettingsSonPencereOtomatikAcilsin)
                {
                    string MRUform = (string)register.GetValue("MRUform", String.Empty);
                    if (MRUform != string.Empty)
                        ShowMdiChildForm(Type.GetType(MRUform));

                    ribbon.SelectedPage = ribbon.Pages[(string)register.GetValue("MRUpage", "rpSatinalma")];
                }

                //DateTime OldTime = DateTime.Now;
                //TimeSpan ts = DateTime.Now - OldTime;
                //string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
                //XtraMessageBox.Show(elapsedTime);

            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show(Ex.ToString());
            }
            

            //foreach (RibbonPage rp in this.Ribbon.Pages)
            //{
            //    bool goster = false;
            //    foreach (RibbonPageGroup rpg in rp.Groups)
            //        goster |= rpg.Visible;
            //    rp.Visible = goster;    //içinde visible group olmayan page leri gizle/gösterme
            //}            


 * * 
 * 
 RepositoryItemGridLookUpEdit riGridLookUp = view.Columns["AksesuarId"].ColumnEdit as RepositoryItemGridLookUpEdit;

                //if (view.IsNewItemRow(e.RowHandle))
                //    e.Value = view.GetRowCellValue(e.RowHandle, e.Column.FieldName);
                object currentKey = view.GetListSourceRowCellValue(e.ListSourceRowIndex, "AksesuarId");
                if (currentKey != null)
                {
                    ConfExpert.Datasets.MyData.AksesuarRow ar = AppSession.Lookups.Aksesuar.FindByAksesuarId(intParse(currentKey));

                    if (ar!=null)                        
                        e.Value = ar[e.Column.FieldName];
                    else
                        e.Value = "";


                    //int lookUpGridSelectedRowIndex = riGridLookUp.GetIndexByKeyValue(currentKey);
                    //if (lookUpGridSelectedRowIndex > -1)
                    //    e.Value = ((riGridLookUp.DataSource as DataTable).Rows[lookUpGridSelectedRowIndex] as DataRow)[e.Column.FieldName];
                    //else
                    //    e.Value = "";
                }* 
 * 
 * 
 * 
 * 
 
        public string sel
        {
            get
            {
                //return cmbTip.EditValue.ToString();
                switch (cmbTip.SelectedIndex)
                {
                    case 1: return "Toplar";
                    case 2: return "Artikeller";
                    case 3: return "Raflar";
                    case 4: return "Askı";
                    case 5: return "StokAlarm";
                    default: return "*Filtre";
                }
            }

            set
            {
                //cmbTip.EditValue = value;
                switch (value)
                {
                    case "*Filtre": cmbTip.SelectedIndex = 0; break;
                    case "Toplar": cmbTip.SelectedIndex = 1; break;
                    case "Artikeller": cmbTip.SelectedIndex = 2; break;
                    case "Raflar": cmbTip.SelectedIndex = 3; break;
                    case "Askı": cmbTip.SelectedIndex = 4; break;
                    case "StokAlarm": cmbTip.SelectedIndex = 5; break;
                }
            }
 * 
 * 
         RepositoryItemComboBox riLine
        {
            get
            {
                RepositoryItemComboBox ri = new RepositoryItemComboBox();
                ri.TextEditStyle = TextEditStyles.DisableTextEditor;
                ri.Items.AddRange(new object[] { "ERKEK", "BAYAN", "ÇOCUK", "ÇOCUK KIZ", "ÇOCUK ERKEK" });
                return ri;
            }
        }

            gv.MoveLast();
            gv.TopRowIndex = gv.FocusedRowHandle;
            gv.MakeRowVisible(gv.FocusedRowHandle, true);
* 
        }* 
 * 
 * 
                 //link: http://www.codeproject.com/Articles/140594/Optimizing-QuickSort

        static void OptimizedQuickSort(ref double[] Arr, int Left, int Right)
        {
            int Pivot;
            Pivot = Q_Sort(ref Arr, Left, Right);
            if (Left < Pivot - 1)
            {
                OptimizedQuickSort(ref Arr, Left, Pivot - 1);
            }
            if (Right > Pivot + 1)
            {
                OptimizedQuickSort(ref Arr, Pivot + 1, Right);
            }
        }

        static int Q_Sort(ref double[] Arr, int Left, int Right)
        {
            double Pivot;
            Pivot = Arr[Left];
            while (Left < Right)
            {
                while ((Arr[Right] >= Pivot) && (Left < Right))
                {
                    Right--;
                }
                if (Left != Right)
                {
                    Arr[Left] = Arr[Right];
                    Left++;
                }
                while ((Arr[Left] <= Pivot) && (Left < Right))
                {
                    Left++;
                }
                if (Left != Right)
                {
                    Arr[Right] = Arr[Left];
                    Right--;
                }
            }
            Arr[Left] = Pivot;
            return Left;
        }  

 * 
 

        ///// <summary>
        ///// method for resizing an image
        ///// </summary>
        ///// <param name="img">the image to resize</param>
        ///// <param name="percentage">Percentage of change (i.e for 105% of the original provide 105)</param>
        ///// <returns></returns>
        //public Image Resize(Image img, int percentage)
        //{
        //    //get the height and width of the image
        //    int originalW = img.Width;
        //    int originalH = img.Height;

        //    //get the new size based on the percentage change
        //    int resizedW = (int)(originalW * percentage);
        //    int resizedH = (int)(originalH * percentage);

        //    //create a new Bitmap the size of the new image
        //    Bitmap bmp = new Bitmap(resizedW, resizedH);
        //    //create a new graphic from the Bitmap
        //    Graphics graphic = Graphics.FromImage((Image)bmp);
        //    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //    //draw the newly resized image
        //    graphic.DrawImage(img, 0, 0, resizedW, resizedH);
        //    //dispose and free up the resources
        //    graphic.Dispose();
        //    //return the image
        //    return (Image)bmp;
        //}


        //[DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory", SetLastError = false)]
        //private static unsafe extern void MoveMemory(void* dest, void* src, int size);

        //public static Bitmap FastCrop(Bitmap image, Rectangle area)
        //{
        //    //Create the new bitmap
        //    Bitmap result = new Bitmap(area.Width,
        //                       area.Height, image.PixelFormat);

        //    unsafe
        //    {
        //        //lock the bits for both bitmaps to
        //        //allow direct access by pointer
        //        BitmapData bmd = image.LockBits(area,
        //            ImageLockMode.ReadOnly, image.PixelFormat);
        //        BitmapData bmdResult = result.LockBits(
        //            new Rectangle(0, 0, area.Width, area.Height),
        //            ImageLockMode.WriteOnly, result.PixelFormat);

        //        int pixelSize =
        //            Image.GetPixelFormatSize(image.PixelFormat) / 8;

        //        //Copy the memory from each row in
        //        //the first bitmap to second
        //        for (int ilkAyrim = 0; ilkAyrim < bmd.Height; ilkAyrim++)
        //        {
        //            byte* to = (byte*)bmdResult.Scan0
        //                           + (ilkAyrim * bmdResult.Stride);
        //            byte* from = (byte*)bmd.Scan0 + (ilkAyrim * bmd.Stride);

        //            MoveMemory(to, from, area.Width * pixelSize);
        //        }

        //        image.UnlockBits(bmd);
        //        result.UnlockBits(bmdResult);
        //    }

        //    return result;
        //}


        /*
        public static class ImageExtensions
        {
            public static Image ScaleToFit(this Image helper, double Height, double Width)
            {
                double percentWidth = (double)Width / (double)helper.Width;
                double percentHeight = (double)Height / (double)helper.Height;

                double multiplier = 0;

                if (percentWidth > percentHeight)
                    multiplier = percentHeight;
                else
                    multiplier = percentWidth;

                return helper.GetThumbnailImage((int)(helper.Width * multiplier), (int)(helper.Height * multiplier), null, IntPtr.Zero);
            }

        }

        
        As rcar says, you can't without losing some quality, the best you can do in c# is:

Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
    gr.SmoothingMode = SmoothingMode.HighQuality;
    gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
    gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
    gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
 * 
 * 
 * 
 * 
 * 
 * 
 *         DataSet dsKstAyrim = null;

        private void TopSec(object sender, EventArgs e)
        {
            dsKstAyrim = Session.DataManager.ExecuteDataSet("GetPreYuklemeKstAyrim", "LFFP2014040010");

            this.Cursor = Cursors.WaitCursor;
            foreach (DataRow dr in dsKstAyrim.Tables[0].Rows)
            {
                int brandId = dr["BrandId"].ToInt(-1);
                int sezonId = dr["SezonId"].ToInt(-1);
                if (brandId * sezonId < 0)
                    throw new ApplicationException("Marka ya da sezon boş !");

                string orderRef = dr["OrderRef"].ToStr();
                decimal hedef = (decimal)dr["YuklenenMt"];
                int productId = dr["ProductId"].ToInt(-1);
                int ayrimId = dr["AyrimId"].ToInt(-1);

                string sheetName = dtArticle.Select("ProductId=" + productId.ToStr())[0]["Article"].ToStr();
                DataRow[] adaySatirlar = dtRoll.Select("Article='" + sheetName + "' and isnull(selected,0) = 0", "Qty");


                Dictionary<int, decimal> rolls = new Dictionary<int, decimal>();

                for (int i = 0; i < adaySatirlar.Length; i++)
                {
                    DataRow drDetail = adaySatirlar[i];
                    rolls.Add(i, (decimal)drDetail["Qty"]);
                }

                List<int> Result = SubsetSum.Select(hedef, rolls);
                foreach (int rowhandle in Result)
                {
                    adaySatirlar[rowhandle]["Selected"] = true;
                    adaySatirlar[rowhandle]["AyrimId"] = ayrimId;
                }
            }

            this.Cursor = Cursors.Default;
        }
 * 
 * 
 * DELETE LAST LINE
 *                  List<string> lines = File.ReadAllLines(file.FullName).ToList();
                    File.WriteAllLines(newfile, lines.GetRange(0, lines.Count - 1).ToArray());

        */


/*
        * ColumnName	RepositoryName
atelye	V_Atelye
contact	V_Contact
dvz	Currency
xdvz	Currency
faturadvz	Currency
xfaturadvz	Currency
malsahibi	V_Customer
owner	V_Customer
customer	V_Customer
user	V_User
employee	V_User
duzenleyen	V_User
talepeden	V_User
sipveren	V_User
siparişeden	V_User
sipariseden	V_User
musteritemsilcisi	V_User
odeyen	V_User
y_fdepo	FDepo
e_fdepo	FDepo
model	V_Model
marka	Brand
mantıksaldepo	Brand
product	V_Kumas
salesagent	V_SalesAgent
salesperson	V_SalesPerson
sipdurumu1	SiparisDurumu1
sipdurumu2	SiparisDurumu2
siparisdurumu	SiparisDurumu2
ongorulenyuklemesekli	YuklemeSekli
xongorulenyuklemesekli	YuklemeSekli
maxongorulenyuklemesekli	YuklemeSekli
gerceklesenyuklemesekli	YuklemeSekli
xgerceklesenyuklemesekli	YuklemeSekli
ongyuklemesekli	YuklemeSekli
revyuklemesekli	YuklemeSekli
geryuklemesekli	YuklemeSekli
ongteslimsekli	TeslimSekli
gerteslimsekli	TeslimSekli
faturadakiteslimsekli	TeslimSekli
xteslimsekli	TeslimSekli
xfaturadakiteslimsekli	TeslimSekli
deporaf	Shelf
y_shelf	Shelf
e_shelf	Shelf
vendor	V_Vendor
uretici	V_Vendor
karbelkalite	Kalite
repository	LookUp
desenrengi	TemelRenk
zeminrengi	TemelRenkler
teamleader	V_TeamLeader
 * 
 * 
 * 
 
        PivotGridField fldPrice;
        void InitPG(PivotGridControl pivot, BindingSource bs)
        {
            pivot.DataSource = bs;
            pivot.BeginUpdate();

            AddNewField(pivot, "PxInvoiceId", PivotArea.FilterArea, 0);
            AddNewField(pivot, "PxInvoiceId", PivotArea.ColumnArea, 0);
            AddNewField(pivot, "ProductId", PivotArea.RowArea, 0).FieldEdit = RI(Rp.V_Kumas);
            AddNewField(pivot, "Qty", PivotArea.DataArea, 0);
            fldPrice = AddNewField(pivot, "Price", PivotArea.DataArea, 1);

            PivotGridField unboundField = pivot.Fields.Add("LineTotal", PivotArea.DataArea);
            unboundField.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
            unboundField.Options.ShowUnboundExpressionMenu = true;
            unboundField.CellFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            unboundField.CellFormat.FormatString = "{0:#,###.##}";
            unboundField.Width = 60;

            //PivotGridField fldLTotal = new PivotGridField("LTotal", PivotArea.DataArea);
            //fldLTotal.Caption = "LTotal";
            //fldLTotal.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
            //fldLTotal.UnboundExpression = "Qty * Price";
            //pivot.Fields.Add(fldLTotal);

            //pivot.Fields["Gramaj"].Appearance.Cell.BackColor = CommonSkins.GetSkin(DevExpress.LookAndFeel.UserLookAndFeel.Default).TranslateColor(SystemColors.Control);
            //pivot.Fields["Gramaj"].Appearance.Cell.ForeColor = Color.Indigo;
            //pivot.Fields["Vendor"].Appearance.Cell.BorderColor = Color.BlueViolet;

            //pivot.OptionsBehavior.ApplyBestFitOnFieldDragging = true;
            //pivot.OptionsView.ShowRowGrandTotals = true;
            //pivot.OptionsView.ShowColumnGrandTotals = true;

            pivot.OptionsView.ShowAllTotals();
            //pivot.Fields["Price"].Options.ShowTotals = false;
            pivot.Fields["Price"].Options.ShowGrandTotal = false;
            pivot.EndUpdate();

            pivot.EditValueChanged += new DevExpress.XtraPivotGrid.EditValueChangedEventHandler(pivotGridControl_EditorValueChanged);
            pivot.FieldValueDisplayText += new PivotFieldDisplayTextEventHandler(pgc_FieldValueDisplayText);
            pivot.CustomDrawCell += new PivotCustomDrawCellEventHandler(pivotGridControl_CustomDrawCell);
            pivot.CustomUnboundFieldData += new CustomFieldDataEventHandler(pivot_CustomUnboundFieldData);
            pivot.CustomCellDisplayText += new PivotCellDisplayTextEventHandler(pivot_CustomCellDisplayText);
            //pivot.CustomSummary += new PivotGridCustomSummaryEventHandler(pivot_CustomSummary);
            //pivot.BestFit();  //pivot.Fields["Qty"]

        }

        void pivot_CustomCellDisplayText(object sender, DevExpress.XtraPivotGrid.PivotCellDisplayTextEventArgs e)
        {
            if (e.DataField == fldPrice && e.RowValueType == DevExpress.XtraPivotGrid.PivotGridValueType.GrandTotal)
                e.DisplayText = string.Empty;

        }

        void pivot_CustomUnboundFieldData(object sender, CustomFieldDataEventArgs e)
        {
            if (e.Field.FieldName == "LineTotal")
            {
                decimal unitPrice = Convert.ToDecimal(e.GetListSourceColumnValue("Price"));
                decimal qty = Convert.ToDecimal(e.GetListSourceColumnValue("Qty"));
                e.Value = unitPrice * qty;
            }
        }

        void pivotGridControl_CustomDrawCell(object sender, DevExpress.XtraPivotGrid.PivotCustomDrawCellEventArgs e)
        {
            if (e.ColumnValueType == PivotGridValueType.Value && e.DataField.FieldName == "LineTotal")
            {
                Rectangle innerRect = Rectangle.Inflate(e.Bounds, -5, -5);
                e.GraphicsCache.DrawString(e.DisplayText, e.Appearance.Font, e.Appearance.GetForeBrush(e.GraphicsCache), innerRect, e.Appearance.GetStringFormat());
                e.Graphics.DrawLine(new Pen(Color.Black, 1), e.Bounds.Right - 2, e.Bounds.Y, e.Bounds.Right - 2, e.Bounds.Bottom);
                e.Handled = true;
            }
        }

        void pgc_FieldValueDisplayText(object sender, PivotFieldDisplayTextEventArgs e)
        {
            if (e.Value != null && e.Field != null && e.Field.FieldEdit != null)
                e.DisplayText = (e.Field.FieldEdit as RepositoryItemGridLookUpEdit).GetDisplayTextByKeyValue(e.Value).ToString();
        }

        private void pivotGridControl_EditorValueChanged(object sender, EditValueChangedEventArgs e)
        {
            try
            {
                PivotDrillDownDataSource ds = e.CreateDrillDownDataSource();
                decimal val = decimal.Parse(e.Editor.EditValue.ToString());
                for (int i = 0; i < ds.RowCount; i++)
                    ds[i][e.DataField.FieldName] = val;
                ((PivotGridControl)sender).RefreshData();

            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
* 
 
        void gvPOSip_RowCellClick(object sender, RowCellClickEventArgs e)
        {

            if (e.Column == gvPOSip.Columns["LastRevNr"])
            {
                int poSipId = gvPOSip.GetRowCellValue(e.RowHandle, "POSipId").ToInt(-1);
                int revnr = e.CellValue.ToInt(-1);
                if (revnr > 0)
                {
                    DataTable dt = ExecDataTable("GetPOSipDosya", poSipId, revnr);

                    using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Blob"]))
                    using (PrintingSystem ps = new PrintingSystem())
                    using (PrintPreviewFormEx preview = new PrintPreviewFormEx())
                    {
                        ps.LoadDocument(ms);
                        preview.PrintingSystem = ps;
                        preview.ShowDialog();
                    }
                }
            }
        }

       


        void gvPOSipLines_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
        {
            if (e.ListSourceRowIndex > -1 && "LineTotal AnlasilanFiyat ToplamTutar".Contains(e.Column.FieldName))
            {
                 CurrencyId	Abbr
                        1	EUR
                        2	USD
                        3	GBP
                        4	TL 
                        5	CHF

                int type = gvPOSip.GetFocusedRowCellValue("CurrencyId").ToInt(-1);
                string prefix = "";
                switch (type)
                {
                    case 1:
                        prefix = "€ ";
                        break;
                    case 2:
                        prefix = "$ ";
                        break;
                    case 3:
                        prefix = "£ ";
                        break;
                    case 4:
                        prefix = "₺ ";
                        break;
                    case 5:
                        prefix = "CHF ";
                        break;
                }

                e.DisplayText = prefix + string.Format("{0:n2}", e.Value);
            }
        }* 
        */

//MailAddress SendFrom = new MailAddress("confexpert@karbel.com");  
//MailAddress To = new MailAddress(to);

//MailMessage message = new MailMessage(SendFrom,To);                

//message.Subject = subject;
//message.IsBodyHtml = true;

//message.Body = body;

//foreach (string cc in commaSeperatedCCMails.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
//{
//    message.CC.Add(cc);
//}



//    foreach (string cc in commaSeperatedCCMails.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
//    {
//        message.CC.Add(cc);
//    }

//    message.Body = body + "<br/><br/> Ekteki dosyayı açarak ilgili forma hızlı bir şekilde ulaşabilirsiniz." ;

//    string path = Session.TempDirectory + "\\ceLink" + DateTime.Now.ToString("ddMMyyyHHmmss") + "_" + Session.CurrentUser.UserId + ".ceLink";

//    using (StreamWriter sw = new StreamWriter(path, true))
//    {
//        sw.WriteLine(command);
//    }

//    Attachment attachFile = new Attachment(path);
//    message.Attachments.Add(attachFile);

//Attachment attachFile = new Attachment(FileToSend);
//message.Attachments.Add(attachFile);

////SmtpClient emailClient = new SmtpClient("78.188.187.118"); //exchange or smtp server goes here.
//SmtpClient emailClient = new SmtpClient("Karbelnt"); //exchange or smtp server goes here.

//emailClient.Credentials = new NetworkCredential("confexpert", "ce2012");
//emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
////emailClient.EnableSsl = true;
//emailClient.Port = 25;  // 465;

//emailClient.Send(message);

/*
The bestFit function works fine now.

But how can i calculate the max height of the vertical columns in the CustomDrawColumnHeader function.
And assign it to the ColumnPanelRowHeight of the grid.

public static void SetBestHeaderHeight(GridView view)
        {
            view.BeginUpdate();
            foreach (GridColumn col in view.VisibleColumns)
            {
                int height = GetVerticalTextHeight(view, col.FieldName);
                view.ColumnPanelRowHeight = Math.Max(height, view.ColumnPanelRowHeight);
            }
            view.EndUpdate();
        }

        private static  int GetVerticalTextHeight(GridView view, string text)
        {
            DevExpress.Utils.AppearanceObject app = view.PaintAppearance.HeaderPanel;
            StringFormat sf = new StringFormat();
            sf.FormatFlags = StringFormatFlags.DirectionVertical;
            SizeF size = view.GridControl.CreateGraphics().MeasureString(text, app.GetFont(), 1000, sf);
            return size.ToSize().Height;
        }

 * 
 * 
 *                 //if (rel.ChildTable.Constraints.Count > 0)
                //    for (int i = 0; i < rel.ChildTable.Constraints.Count; i++)
                //    {
                //        Constraint con = rel.ChildTable.Constraints[i];
                //        if (con is ForeignKeyConstraint)
                //            rel.ChildTable.Constraints.Remove(con);
                //    }


*/